백준 문제풀이/실버5
백준 11651번 - 좌표 정렬하기 2
void_melody
2022. 2. 15. 21:02
https://www.acmicpc.net/problem/11651
11651번: 좌표 정렬하기 2
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
www.acmicpc.net
x, y 좌표 두 개가 필요해서 이차원 배열을 활용하는 방법도 있지만, pair 자료형을 사용해봤다.
약간 특이한 점이 있다면, y좌표를 기점으로 둬야한다는 것이다.
그렇기에 기존의 sort함수를 활용할 때 추가적인 기능을 같이 넣어줘야한다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(pair<int, int> a, pair<int, int> b)
{
if (a.second == b.second)
return a.first < b.first;
else
return a.second < b.second;
}
int main()
{
std::cin.tie(NULL);
std::ios::sync_with_stdio(false);
int n;
cin >> n;
std::vector<std::pair<int, int>> v(n);
for (int i = 0; i < n; i++)
cin >> v[i].first >> v[i].second;
sort(v.begin(), v.end(), compare);
for (int i = 0; i < n; i++)
cout << v[i].first << ' ' << v[i].second << '\n';
return 0;
}
sort 함수 활용할 때 이렇게 추가적인 함수를 선언하는 경우를 문제 풀면서 종종 보는 것 같다.
기억하자..!!