문제
https://www.acmicpc.net/problem/11651
문제 요약
2차원 평면의 점 n개가 주어졌을 때, 정렬하여 출력한다.
< 정렬 방법 >
1. y좌표가 증가하는 순서로 정렬한다.
2. y좌표가 같다면 x좌표가 증가하는 순서로 정렬한다.
코드
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
using namespace std;
int n;
vector<tuple<int, int>> arr;
// 정렬 조건
bool compare(tuple<int, int> a, tuple<int, int> b) {
if (get<1>(a) == get<1>(b)) {
return get<0>(a) < get<0>(b);
}
return get<1>(a) < get<1>(b);
}
int main() {
// 입력
cin >> n;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
arr.push_back({ x,y });
}
// compare를 기준으로 arr 정렬
sort(arr.begin(), arr.end(), compare);
// 출력
for (int i = 0; i < n; i++) {
int x, y;
tie(x, y) = arr[i];
cout << x << " " << y << "\n";
}
return 0;
}
코드 설명
1. x, y좌표를 튜플로 감싸 arr 벡터에 저장한다.
2. compare 함수와 sort 함수를 이용해 주어진 조건으로 arr를 정렬하고, 출력한다.
고찰
튜플 내 요소를 인덱스를 통해 접근할 때 필요한 get 함수에 대해 알아두자.
=> get<인덱스 번호>(튜플 변수 이름)
'Algorithm Problems > 정렬' 카테고리의 다른 글
[백준/C++] 10814번: 나이순 정렬 (1) | 2024.05.03 |
---|---|
[백준/C++] 10989번: 수 정렬하기 3 (0) | 2024.04.28 |
[백준/C++] 11650번: 좌표 정렬하기 (0) | 2024.04.14 |
[백준/Python] 1302번: 베스트셀러 (0) | 2023.10.09 |
[백준/python] 8979번: 올림픽 (0) | 2023.07.26 |