PS/Java
[백준 11650] 좌표 정렬하기
siyamaki
2022. 4. 1. 10:32
2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
출력
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
예제 입력 1
5
3 4
1 1
1 -1
2 2
3 3
예제 출력 1
1 -1
1 1
2 2
3 3
3 4
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class Main {
public static class Point implements Comparable<Point> {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point o) {
if(this.x == o.x) {
return this.y - o.y;
}
return this.x - o.x;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
ArrayList<Point> list = new ArrayList<>();
for(int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
list.add(new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())));
}
Collections.sort(list);
for(int i = 0; i < N; i++) {
bw.write(list.get(i).x + " " + list.get(i).y);
bw.newLine();
}
br.close();
bw.flush();
bw.close();
}
}
x좌표가 증가하는 순, x 좌표가 같으면 y좌표가 증가하는 순으로 정렬이다.
Comparable인터페이스를 상속받아 compareTo를 재정의하였다.