[백준_11650] 좌표 정렬하기

MyungHwan Kim·2022년 9월 1일

백준

목록 보기
20/39
post-thumbnail

문제

백준 11650번
https://www.acmicpc.net/problem/11650

2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.

Code

  • 점의 좌표 순으로 우선순위 큐에 넣는다.
  • 하지만 위 그림처럼 우선순위 큐에 들어가게 된다.

Java

import java.io.*;
import java.util.*;

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) {
        // x 좌표가 같을 경우
        if (this.x == o.x) {
            // y 좌표가 증가하는 순서
            return this.y - o.y;
        }
        // x 좌표가 순서하는 순서
        return this.x - o.x;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());  // 평면 위 점의 개수
        PriorityQueue<Point> pq = new PriorityQueue<>();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            pq.offer(new Point(x, y));
        }

        while (!pq.isEmpty()) {
            Point cur = pq.poll();
            sb.append(cur.x).append(" ").append(cur.y).append("\n");

            // 우선순위 큐가 비어있을 경우
            if (pq.isEmpty()) {
                break;
            }
        }
        System.out.println(sb);
    }
}
profile
Back-end 개발자가 되기 위한 개발 노트(Java)

0개의 댓글