on
[알고리즘/백준] 11651 좌표 정렬하기2(자바)
[알고리즘/백준] 11651 좌표 정렬하기2(자바)
문제
https://www.acmicpc.net/problem/11651
풀이 코드
x,y 좌표를 표현할 Pos 클래스를 만들고, Comparable을 구현하여 정렬 기준을 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 만든다.
좌표 값들을 입력 받아 Pos타입 배열에 저장하고 배열을 정렬한 후 출력한다.
StringBuilder를 사용하여 한번에 모아 출력함으로써 실행 시간 단축
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static class Pos implements Comparable{ int x; int y; public Pos(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pos o) { if (this.y == o.y) { return this.x - o.x; } else { return this.y - o.y; } } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); Pos[] arr = new Pos[n]; for (int i = 0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); arr[i] = new Pos(x, y); } Arrays.sort(arr); for (Pos pos : arr) { sb.append(pos.x).append(" ").append(pos.y).append("
"); } System.out.println(sb); } }
728x90
from http://developer-hm.tistory.com/183 by ccl(A) rewrite - 2021-10-05 18:01:32