정신과 시간의 방
카테고리
작성일
2024. 6. 26. 17:23
작성자
risehyun
  • 문제

 

  • 풀이
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() 
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);

	int n = 0;
	cin >> n;

	vector<pair<int, int>> points(n);

	for (int i = 0; i < n; i++)
	{
		cin >> points[i].first >> points[i].second;
	}

	sort(points.begin(), points.end());

	for (int i = 0; i < n; i++)
	{
		cout << points[i].first << ' ' << points[i].second << '\n';
	}

	return 0;
}

 

 

  • 메모
    utility 라이브러리에 속하며 algorithm, vector 라이브러리에 기본 헤더로 선언되어 있는 sort와 pair를 사용해서 풀면 간단한 문제다.

    sort() 함수는 기본적으로 첫번째 원소로 들어온 값을 기준으로 정렬을 하다가, 두 값이 같은 경우에는 두번째 원소로 들어온 값을 기준으로 정렬하게 된다.

    따라서 문제에서 요구하는 모든 조건을 충족하게 된다.

 

  • 오답노트
    동적 할당을 하고 비교조건을 걸어서 하나씩 swap해주는 방법을 사용했는데
    지금 생각해보니 동적 할당 대신 처음부터 고정 메모리를 써도 됬을 것 같고
    코드도 vector의 sort 기능을 사용하는게 훨씬 간결하다.

    이런 센스는 경험이 쌓이면 좀 나아지겠지? 문제를 더 많이 풀어야겠다.
#include <iostream>

using namespace std;

struct Point
{
	int x;
	int y;
};

int main() 
{
	int n = 0;

	cin >> n;

	Point* input = new Point[n];

	for (int i = 0; i < n; i++)
	{
		cin >> input[i].x >> input[i].y;
	}

	for (int i = 0; i < n - 1; i++)
	{
		if (input[i].x > input[i + 1].x)
		{
			Point temp = input[i];
			input[i] = input[i + 1];
			input[i + 1] = temp;
		}
		if (input[i].x == input[i + 1].x)
		{
			if (input[i].y > input[i + 1].y)
			{
				Point temp = input[i];
				input[i] = input[i + 1];
				input[i + 1] = temp;
			}
		}
	}

	for (int i = 0; i < n; i++)
	{
		cout << input[i].x << " " << input[i].y << '\n';
	}

	delete[] input;

	return 0;
}