smooth waters run deep

1d-1c/BOJ

11650_좌표 정렬하기 (JAVA)

yeon_11 2020. 12. 4. 14:50
 

11650번: 좌표 정렬하기

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

www.acmicpc.net

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;


public class Main {
	static class XY implements Comparable<XY>{
		int x; int y;
		public XY(int x, int y){
			this.x=x; this.y=y;
		}

		@Override
		public int compareTo(XY xy) {
			if(this.x > xy.x)
				return 1;
			else if(this.x == xy.x)
				if(this.y > xy.y)
					return 1;
			return -1;
		}
	}
    
    public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		StringTokenizer st;

		int n = Integer.parseInt(br.readLine());
		XY[] arr = new XY[n];
		for(int i=0; i<n; i++){
			st = new StringTokenizer(br.readLine());
			arr[i] = new XY(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
		}

		Arrays.sort(arr);

		for(int i=0; i<n; i++){
			sb.append(arr[i].x+" "+arr[i].y).append('\n');
		}

		System.out.print(sb);
		br.close();
    }
}

 

 

 

 

 

** Comparable 인터페이스 참조!

 

Comparable interface (객체 정렬)

Comparable 이란? - java.lang.Comparable 패키지에 속해 있으며, Comparable 인터페이스를 이용해 객체를 정렬할 수 있다. 구현 방법 1. 객체에 Comparable 인터페이스를 implements 한다. 2. compareTo() 메서드..

yeone2ee.tistory.com

 

'1d-1c > BOJ' 카테고리의 다른 글

10814_나이순 정렬 (JAVA)  (0) 2020.12.05
1181_단어 정렬 (JAVA)  (0) 2020.12.04
1427_소트인사이드 (JAVA)  (0) 2020.12.04
1707_이분 그래프 (JAVA)  (0) 2020.12.03
13023_ABCDE (JAVA)  (0) 2020.12.03