11650번: 좌표 정렬하기 (acmicpc.net)
11650번: 좌표 정렬하기
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
www.acmicpc.net
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<pair<int, int>> v(n);
for (auto &i: v) {
cin >> i.first >> i.second;
}
sort(v.begin(), v.end());
for (auto i: v) {
cout << i.first << ' ' << i.second << '\n';
}
return 0;
}
sort 함수는 비교 함수를 명시하지 않으면 오름차순으로 정렬하는데,
pair<int, int>의 경우 첫번째 요소가 증가하는 순으로, 같으면 두번째 요소가 증가하는 순으로 정렬한다.
#include <iostream>
#include <algorithm>
using namespace std;
struct Pos {
int x, y;
bool operator<(const Pos &other) const {
if (x == other.x) return y < other.y;
return x < other.x;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<Pos> v(n);
for (auto &i: v) {
cin >> i.x >> i.y;
}
sort(v.begin(), v.end());
for (auto i: v) {
cout << i.x << ' ' << i.y << '\n';
}
return 0;
}
직접 비교 함수를 만들 수도 있다.