반응형

문제

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

입력

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

출력

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

 

Java Solution

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

public class Main {
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tokenizer;
        
        int n = Integer.parseInt(br.readLine());
        Location[] locations = new Location[n];
        for(int i = 0; i < n; i++) {
            tokenizer = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(tokenizer.nextToken());
            int y = Integer.parseInt(tokenizer.nextToken());
            locations[i] = new Location(x, y);
        }
        
        Arrays.sort(locations);
        for(Location location : locations) {
            System.out.println(location.x + " " + location.y);
        }
    }
    
    private static class Location implements Comparable<Location> {
        int x;
        int y;
        
        private Location(int x, int y) {
            this.x = x;
            this.y = y;
        }
        
        @Override
        public int compareTo(Location o) {
        	int cx = x - o.x;
            return (cx != 0) ? cx : y - o.y;
        }
    }
}

Comparable<>을 사용하여 정렬했습니다.

반응형
반응형