파게로그

[백준 11650번] 좌표 정렬하기 본문

콤퓨타 왕왕기초/PS

[백준 11650번] 좌표 정렬하기

파게 2020. 11. 15. 16:21

문제 링크: 11650번 좌표 정렬하기

https://www.acmicpc.net/problem/11650

 

Pos라는 클래스를 새로 생성했기에, Comparator나 Comparable 둘 중 어느 것을 써도 관계없다.

 

import java.util.*;

class Pos {
    int x;
    int y;
    
    public Pos(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public String toString() {
        return x + " " + y;
    }
}

public class Main {
    public static void main(String[] args) {
        /* 입력 */
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        sc.nextLine();
        ArrayList<Pos> list = new ArrayList<Pos>();
        for (int i = 0; i < n; i++) {
            String s[] = sc.nextLine().split(" ");
            Pos p = new Pos(Integer.parseInt(s[0]), Integer.parseInt(s[1]));
            list.add(p);
        }
        
        /* 정렬 */
        Comparator<Pos> posComparator = new Comparator<Pos>() {
            @Override
            public int compare(Pos p1, Pos p2) {
                if (p1.x < p2.x) return -1;
                else if (p1.x > p2.x) return 1;
                else {
                    if (p1.y < p2.y) return -1;
                    else if (p1.y > p2.y) return 1;
                    else return 0;
                }
            }
        };
        
        Collections.sort(list, posComparator);
        
        /* 출력 */
        for (Pos item : list) {
            System.out.println(item.toString());
        }
    }
}

 

Comments