2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
#include <iostream>
#include <algorithm>
#include <utility>
using namespace std;
bool comp(pair<int, int> a, pair<int, int> b) {
if(a.first == b.first) {
return a.second < b.second;
} else {
return a.first < b.first;
}
}
int main() {
int N, x, y;
pair<int, int> input[100000];
scanf("%d", &N);
for(int i = 0; i < N; i++) {
scanf("%d%d", &x, &y);
input[i] = make_pair(x, y);
}
sort(input, input+N, comp);
for(int i = 0; i < N; i++) {
printf("%d %d\n", input[i].first, input[i].second);
}
}
data가 한 쌍으로 있는 경우이다.
pair로 데이터를 묶어 <int, int> 배열로 만들었고,
algorithm 헤더의 sort를 사용해 배열을 정렬해주었다.
이 때, comp함수를 만들어주어, 조건에 맞게 비교할 수 있도록 해주었다.