파게로그

[백준 11651번] 좌표 정렬하기 2 본문

콤퓨타 왕왕기초/PS

[백준 11651번] 좌표 정렬하기 2

파게 2020. 11. 15. 13:35

문제 링크: 11651번 좌표 정렬하기 2

https://www.acmicpc.net/problem/11651

 

정렬에 대해서 특별한 것은 없다. 다만 nextInt()가 입력받는 것은 정수까지이다. 정수 뒤의 \n은 바로 뒤의 nextLine()이 입력받기에 Exception이 발생한다. 따라서 nextLine()을 사용하기 전, nextLine()을 한 번 더 호출하여 \n를 처리하도록 한다.

 

import java.util.*; class Pos implements Comparable<Pos> { ​​​​int x; ​​​​int y; ​​​​ ​​​​public Pos(int x, int y) { ​​​​​​​​this.x = x; ​​​​​​​​this.y = y; ​​​​} ​​​​ ​​​​public String toString() { ​​​​​​​​return x + " " + y; ​​​​} ​​​​ ​​​​public int compareTo(Pos p) { ​​​​​​​​if (this.y > p.y) return 1; ​​​​​​​​else if (this.y < p.y) return -1; ​​​​​​​​else return this.x - p.x; ​​​​} } public class Main { ​​​​public static void main(String[] args) { ​​​​​​​​/* input */ ​​​​​​​​Scanner sc = new Scanner(System.in); ​​​​​​​​int n = sc.nextInt(); ​​​​​​​​Pos[] arr = new Pos[n]; ​​​​​​​​ ​​​​​​​​sc.nextLine(); // nextInt() 뒤 '\n' 처리 ​​​​​​​​for (int i = 0; i < n; i++) { ​​​​​​​​​​​​int x, y; ​​​​​​​​​​​​String[] line = sc.nextLine().split(" "); ​​​​​​​​​​​​x = Integer.parseInt(line[0]); ​​​​​​​​​​​​y = Integer.parseInt(line[1]); ​​​​​​​​​​​​Pos p = new Pos(x, y); ​​​​​​​​​​​​arr[i] = p; ​​​​​​​​} ​​​​​​​​ ​​​​​​​​/* sort */ ​​​​​​​​Arrays.sort(arr); ​​​​​​​​ ​​​​​​​​/* output */ ​​​​​​​​for (Pos p : arr) { ​​​​​​​​​​​​System.out.println(p.toString()); ​​​​​​​​} ​​​​​​​​sc.close(); ​​​​} }
Comments