티스토리 뷰

반응형

문제

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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Q11650 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tokenizer;

        int countLocation = Integer.parseInt(br.readLine());
        SortLocation[] sortLocations = new SortLocation[countLocation];

        for (int i = 0; i < countLocation; i++) {
            tokenizer = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(tokenizer.nextToken());
            int y = Integer.parseInt(tokenizer.nextToken());
            sortLocations[i] = new SortLocation(x, y);
        }

        Arrays.sort(sortLocations);

        for (SortLocation sortLocation : sortLocations) {
            System.out.println(sortLocation.getX() + " " + sortLocation.getY());
        }

    }
}

class SortLocation implements Comparable {
    private int x;
    private int y;

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }


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

    @Override
    public int compareTo(SortLocation o) {
        if (this.x < o.x) {
            return -1;
        } else if (this.x == o.x) {
            if (this.y < o.y) {
                return -1;
            } else if (this.y == o.y) {
                return 0;
            } else {
                return 1;
            }
        }
        return 1;
    }
}

 

 

 

반응형

'Algorithms > BOJ' 카테고리의 다른 글

백준 Q.1157 단어 공부  (0) 2020.01.08
백준 Q.1159 농구 경기  (0) 2020.01.08
백준 Q.1302 베스트셀러  (0) 2020.01.07
백준 Q.9375 패션왕 신해빈  (0) 2020.01.06
백준 Q.10814 나이 순 정렬하기  (0) 2020.01.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함