ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 11650번 - 좌표 정렬하기
    알고리즘/백준 2023. 6. 6. 13:41
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.StringTokenizer;
    
    public class Main {
    	
    	static class Point implements Comparable<Point> {
    		int x;
    		int y;
    		
    		Point(int x, int y) {
    			this.x = x;
    			this.y = y;
    		}
    		
    		@Override
    		public int compareTo(Point p) {
    			if(x != p.x) {
    				return x-p.x;
    			} else {
    				return y-p.y;
    			}
    		}
    	}
    	
    	public static void main(String[] args) throws IOException {
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		int N = Integer.parseInt(br.readLine());
    		ArrayList<Point> list = new ArrayList<>();
    		StringTokenizer st;
    		StringBuilder sb = new StringBuilder();
    		for(int i=0;i<N;i++) {
    			st = new StringTokenizer(br.readLine());
    			list.add(new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())));
    		}
    		list.sort(null);
    		Point point;
    		for(int i=0;i<N;i++) {
    			point = list.get(i);
    			sb.append(point.x+" "+point.y+"\n");
    		}
    		System.out.println(sb);
    		br.close();
    	}
    }

    역시 정렬 문제이기 때문에 Comparable을 implement한 클래스와 ArrayList의 sort 메서드를 이용합니다.

    이 때 x를 먼저 비교하고 같은 경우에만 y를 비교해야 하기 때문에 compareTo 메서드를 if문을 통해 x가 다를 경우 x에 대해 오름차순, 같을 경우 y에 대해 오름차순으로 정의했습니다. 또한 StringBuilder를 사용해야 합니다.

    '알고리즘 > 백준' 카테고리의 다른 글

    11866번 - 요세푸스 문제 0  (0) 2023.06.06
    11651번 - 좌표 정렬하기 2  (0) 2023.06.06
    1676번 - 팩토리얼 0의 개수  (2) 2023.06.06
    10866번 - 덱  (0) 2023.06.06
    10845번 - 큐  (2) 2023.06.06
Designed by Tistory.