티스토리 뷰

문제

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

입력

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

출력

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

예제 입력 

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

예제 출력 

1 -1
1 1
2 2
3 3
3 4


코드

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package sort;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
 
class XY {
    int x;
    int y;
    
    public XY( int x, int y){
        this.x = x;
        this.y = y;
    }
    
}
 
/**
 * https://www.acmicpc.net/problem/11650
 * 좌표 정렬하기
 * @author minjung
 *
 */
public class baekjoon_11650 {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        
        int N = sc.nextInt();
        
        ArrayList<XY> arr = new ArrayList<XY>();
        for ( int i = 0; i < N; i++ ){
            int x = sc.nextInt();
            int y = sc.nextInt();
            
            arr.add(new XY(x, y));
        }
        
        Collections.sort(arr, new Comparator<XY>() {
 
            @Override
            public int compare(XY o1, XY o2) {
                if ( o1.x > o2.x ){
                    return 1;
                }
                else if ( o1.x < o2.x ){
                    return -1;
                }
                else {
                    if ( o1.y > o2.y ){
                        return 1;
                    }
                    else if (o1.y < o2.y ){
                        return -1;
                    }
                    else {
                        return 0;
                    }
                }
            }
        });
        
        for ( int i = 0; i < arr.size(); i++ ){
            System.out.println(arr.get(i).x + " " + arr.get(i).y);
        }
    }
 
}
 
cs


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 31
글 보관함