Algorithm
[백준-18870번/Java] 좌표 압축
1984
2022. 11. 17. 23:53
* 문제) 전체 좌표들 중에서 각 좌표값보다 작은 값을 가지는 좌표의 갯수를 출력하는 문제.
* Point 라는 class에 좌표값(x)과 index 를 저장한 후, compareTo method를 사용해서 풀었다.
* 정렬한 배열을 따로 저장해 놓고, 좌표값을 앞에서 부터 찾는 방식으로 풀어도 될 것 같다.
import java.io.*;
import java.util.*;
public class Main {
private static class Point implements Comparable {
int x;
int index;
public Point(int x, int index) {
this.x = x;
this.index = index;
}
public Integer getX() {
return this.x;
}
@Override
public String toString() {
return x + "(" + index + ")";
}
@Override
public int compareTo(Object o) {
Point p = (Point) o;
return getX().compareTo(p.getX());
}
}
@SuppressWarnings("unchecked")
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());
StringTokenizer stk = new StringTokenizer(br.readLine(), " ");
ArrayList<Point> arr = new ArrayList<Point>();
for (int i = 0; i < N; i++) {
arr.add(new Point(Integer.parseInt(stk.nextToken()), i));
}
int[] answer = new int[N];
Collections.sort(arr);
int check_x = -1000000001;
int check_count = -1;
for (Point point : arr) {
if (check_x != point.x) {
check_count++;
}
answer[point.index] = check_count;
check_x = point.x;
}
for (int i = 0; i < answer.length; i++) {
bw.write(answer[i] + " ");
}
bw.flush();
}
}
728x90