본문 바로가기

백준 11651번 좌표 정렬하기2

@6uiw2026. 1. 15. 22:04

문제

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

입력

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

출력

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

예제 입력 1 

5
0 4
1 2
1 -1
2 2
3 3

예제 출력 1 

1 -1
1 2
2 2
3 3
0 4
 

 

풀이

import java.awt.Point;
import java.io.IOException;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) throws IOException {
        int n = readInt();
        StringBuilder sb = new StringBuilder();

        Point[] points = new Point[n];
        int x; int y;
        for(int i = 0; i < n; i++){
            x  = readInt();
            y  = readInt();
            points[i] = new Point(x, y);

        }
        
        Arrays.sort(points, (p1, p2) -> {
            if (p1.y != p2.y) {
                return Integer.compare(p1.y, p2.y); 
            }
            return Integer.compare(p1.x, p2.x);     
        });

        for (Point p : points) {
            sb.append(p.x + " " + p.y+"\n");
        }
        
        System.out.println(sb.toString());

    }

    private static int readInt() throws IOException {
        int out = 0;
        boolean negative = false;

        while (true) {
            int n = System.in.read();
            if(n<=32) return negative? (-1)*out:out;
            else if (n == '-') negative = true;
            else out = (out <<3) + (out<<1) + (n-'0');
        }

    }

}

 

 
 

Point : 자바에서 좌표(두 값)를 담기 위한 클래스 

 

  • x, y 두 개의 정수 값을 한 묶음으로 표현
  • 좌표, 위치, (n, m) 같은 데이터 표현에 자주 사용

내부 구조:

public class Point {
    public int x;
    public int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

 

6uiw
@6uiw :: LOG.INFO("MING's DEVLOG")

개발을 하면서 공부한 기록을 남깁니다

목차