본문 바로가기
PS 문제 풀이/Baekjoon

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

by 까망 하르방 2021. 2. 26.
반응형

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

 Input 

5

3 4

1 1

1 -1

2 2

3 3

 

 Output 

1 -1

1 1

2 2

3 3

3 4 

Java API 중 Comparator를 이용해 정렬

 


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 st = null;
        
        int N = Integer.parseInt(br.readLine());
        
        List<Point> list = new ArrayList<Point>();
        for(int i=0; i<N; i++) {
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            list.add(new Point(x, y));
        }
        Comparator<Point> xComparator = new xComparator();
        Comparator<Point> yComparator = new yComparator();
        Collections.sort(list, new ChainedComparator(
                xComparator, 
                yComparator
        ));
 
        for(int i=0; i<N; i++)
            System.out.println(list.get(i));
    }
}
 
class xComparator implements Comparator<Point> {
    // x 좌표 기준 오름차순 정렬
    @Override
    public int compare(Point p1, Point p2) {
        return p1.x - p2.x;
    }
 
}
 
class yComparator implements Comparator<Point> {
    // y 좌표 기준 오름차순 정렬
    @Override
    public int compare(Point p1, Point p2) {
        return p1.y - p2.y;
    }
 
}
 
class ChainedComparator implements Comparator<Point> {
    private List<Comparator<Point>> listComparators;
    @SafeVarargs
    public ChainedComparator(Comparator<Point>... comparators)  {
          this.listComparators = Arrays.asList(comparators);
    }
    @Override
    public int compare(Point p1, Point p2) {
          for (Comparator<Point> comparator : listComparators)  {
               int result = comparator.compare(p1, p2);
               if (result != 0) {
                     return result;
               }
          }
          return 0;
    }
}
 
class Point {
    int x, y;
 
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
 
    @Override
    public String toString() {
        return x + " " + y;
    }
}

 

반응형

댓글