공log/[P&B]

[P&B] #79 BAEKJOON 11650

ming_OoO 2023. 9. 22. 20:24
728x90

백준 11650번 JAVA 좌표 정렬하기

문제 설명

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

 

입력

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

 

출력

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

 

나의 문제 풀이 코드

import java.util.*;
import java.io.*;
public class bj11650 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int N = Integer.parseInt(br.readLine());
        String[] point = new String[N];
        for (int i = 0; i < N; i++) {
            point[i] = br.readLine();
        }

        Arrays.sort(point, new Comparator<String>() {
            public int compare(String s1, String s2) {
                String[] split1 = s1.split(" ");
                String[] split2 = s2.split(" ");
                int age1 = Integer.parseInt(split1[0]);
                int age2 = Integer.parseInt(split2[0]);

                if (age1 == age2)
                    return Integer.compare(Integer.parseInt(split1[1]),Integer.parseInt(split2[1]));
                else
                    return Integer.compare(age1, age2);
            }
        });

        for (String str :
                point) {
            bw.write(str+"\n");
        }
        bw.flush();
    }
}

 

문제 풀이 코멘트

이 문제는 이전 문제의 풀이와 비슷하게 하였다. 다만 달라진게 있다면 x좌표가 같을 땐 y좌표의 오름차순으로 정렬해야하기 때문에 조건식을 걸어 한번 더 비교하여 정렬되도록 하였다.

728x90

'공log > [P&B]' 카테고리의 다른 글

[P&B] #81 BAEKJOON 10816  (0) 2023.09.23
[P&B] #80 BAEKJOON 11866  (0) 2023.09.22
[P&B] #78 BAEKJOON 10814  (0) 2023.09.21
[P&B] #77 BAEKJOON 1181  (0) 2023.09.21
[P&B] #76 BAEKJOON 1920  (0) 2023.09.21