[BaekJoon] #11650 - 좌표 정렬하기 [Java][C++]
[BaekJoon] #11650 - 좌표 정렬하기 [Java][C++]
1. 아이디어
주어진 좌표를 $x$ 좌표에 대한 오름차순으로, $x$ 좌표가 같다면 $y$ 좌표에 대한 오름차순으로 정렬하는 간단한 문제다. 다만 $N$이 최대 $100{,}000$이라서 $O(N^2)$보다 빠른 정렬 알고리즘이 필요하다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N \log N)$ | $O(N)$ |
($N$ = 입력값 n)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
int[][] arr = new int[n][2];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
arr[i][0] = Integer.parseInt(st.nextToken());
arr[i][1] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr, (o1, o2) -> {
if (o1[0] != o2[0]) return Integer.compare(o1[0], o2[0]);
return Integer.compare(o1[1], o2[1]);
});
for (int[] pos : arr) {
sb.append(pos[0]).append(" ").append(pos[1]).append("\n");
}
System.out.println(sb);
}
}
2차원 배열로 좌표를 입력받고 람다식을 활용하여 정렬 후 출력했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<pair<int, int>> v(n);
for (auto& [x, y] : v) cin >> x >> y;
sort(v.begin(), v.end());
for (auto [x, y] : v) {
cout << x << ' ' << y << '\n';
}
}
좌표를 std::pair로 다루고 이를 받은 벡터를 정렬했다. std::pair는 first에 대한 오름차순, first가 같으면 second에 대한 오름차순으로 정렬돼서 좌표 정렬과 기준이 동일하다.
This post is licensed under CC BY 4.0 by the author.