반응형
출처: https://www.acmicpc.net/problem/11650
Input
5
3 4
1 1
1 -1
2 2
3 3
Output
1 -1
1 1
2 2
3 3
3 4
Java API 중 Comparator를 이용해 정렬
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));
StringTokenizer st = null;
int N = Integer.parseInt(br.readLine());
List<Point> list = new ArrayList<Point>();
for(int i=0; i<N; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
list.add(new Point(x, y));
}
Comparator<Point> xComparator = new xComparator();
Comparator<Point> yComparator = new yComparator();
Collections.sort(list, new ChainedComparator(
xComparator,
yComparator
));
for(int i=0; i<N; i++)
System.out.println(list.get(i));
}
}
class xComparator implements Comparator<Point> {
// x 좌표 기준 오름차순 정렬
@Override
public int compare(Point p1, Point p2) {
return p1.x - p2.x;
}
}
class yComparator implements Comparator<Point> {
// y 좌표 기준 오름차순 정렬
@Override
public int compare(Point p1, Point p2) {
return p1.y - p2.y;
}
}
class ChainedComparator implements Comparator<Point> {
private List<Comparator<Point>> listComparators;
@SafeVarargs
public ChainedComparator(Comparator<Point>... comparators) {
this.listComparators = Arrays.asList(comparators);
}
@Override
public int compare(Point p1, Point p2) {
for (Comparator<Point> comparator : listComparators) {
int result = comparator.compare(p1, p2);
if (result != 0) {
return result;
}
}
return 0;
}
}
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
반응형
'PS 문제 풀이 > Baekjoon' 카테고리의 다른 글
[BOJ] 백준 14681 사분면 고르기 (0) | 2021.02.26 |
---|---|
[BOJ] 백준 11651 좌표 정렬하기 2 (0) | 2021.02.26 |
[BOJ] 백준 1605 반복 부분문자열 (0) | 2021.02.26 |
[BOJ] 백준 9248 Suffix Array (0) | 2021.02.26 |
[BOJ] 백준 11656 접미사 배열 (0) | 2021.02.26 |
댓글