ALGORITHM
백준 11651 좌표 정렬하기2 (Java)
공부하는_다온
2023. 5. 22. 23:00
1. 문제 링크
11651번: 좌표 정렬하기 2
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
www.acmicpc.net
2. 문제 및 입출력예제
3. 문제 풀이
각 좌표들을 Point 객체로 PQ에 넣는다.
y좌표 기준으로 비교하고 x 좌표 기준으로 비교해 정렬한다.
pq를 x좌표 y좌표 순으로 출력하면 끝이다.
4. 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
public class Main {
static class Point implements Comparable<Point>{
int x;
int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point o) {
if(this.y==o.y) {
return this.x-o.x;
}
return this.y-o.y;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
PriorityQueue<Point> pq = new PriorityQueue<>();
for(int i=0;i<N;i++) {
String[] split = br.readLine().split(" ");
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
pq.offer(new Point(x, y));
}
while(!pq.isEmpty()) {
Point p = pq.poll();
System.out.println(p.x+" "+p.y);
}
}
}