Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-18870번/Java] 좌표 압축 본문

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();

	}
}
Comments