본문 바로가기

ALGORITHM

백준 11651 좌표 정렬하기 2 (Java)

1. 문제 링크

 

11651번: 좌표 정렬하기 2

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

www.acmicpc.net

 

2. 문제 및 입출력예제

 

3. 문제 풀이

입력받은 x, y를 Point에 넣는다.

Comparable를 이용해서 y 좌표가 같을 경우 x 좌표를 비교하게 한다.

Point를 넣은 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);
		}
	}
}

 

'ALGORITHM' 카테고리의 다른 글

백준 15685 드래곤 커브 (Java)  (0) 2023.06.10
백준 1915 가장 큰 정사각형 (Java)  (0) 2023.06.09
백준 5052 전화번호 목록 (Java)  (0) 2023.06.07
백준 1303 전쟁 - 전투 (Java)  (0) 2023.06.06
백준 1461 도서관 (Java)  (0) 2023.06.05