[BOJ] 15970번 : 화살표 그리기

ErroredPasta·2022년 4월 1일
0

문제

직선 위에 위치를 나타내는 0, 1, 2, ...와 같은 음수가 아닌 정수들이 일정한 간격으로 오른쪽 방향으로 놓여 있다. 이러한 위치들 중 N개의 위치에 하나씩 점들이 주어진다(<그림 1>). 주어진 점들의 위치는 모두 다르다. 두 점 사이의 거리는 두 점의 위치를 나타내는 수들의 차이이다. <그림 1>에서는 4개의 점이 주어지고 점 a와 b의 거리는 3이다.


<그림 1>

각 점은 N개의 색깔 중 하나를 가진다. 편의상, 색깔은 1부터 N까지의 수로 표시한다.

각 점 p에 대해서, p에서 시작하는 직선 화살표를 이용해서 다른 점 q에 연결하려고 한다. 여기서, 점 q는 p와 같은 색깔의 점들 중 p와 거리가 가장 가까운 점이어야 한다. 만약 가장 가까운 점이 두 개 이상이면 아무거나 하나를 선택한다.

모든 점에 대해서 같은 색깔을 가진 다른 점이 항상 존재한다. 따라서 각 점 p에서 시작하여 위 조건을 만족하는 q로 가는 하나의 화살표를 항상 그릴 수 있다.

예를 들어, 점들을 순서쌍 (위치, 색깔) 로 표시할 때, a = (0,1), b = (1, 2), c = (3, 1), d = (4, 2), e = (5, 1)라고 하자.

아래 <그림 2>에서 이 점들을 표시한다. 여기서 흰색은 1, 검은색은 2에 해당된다.


<그림 2>

위의 조건으로 화살표를 그리면, 아래 <그림 3>과 같이 점 a의 화살표는 c로 연결된다. 점 b와 d의 화살표는 각각 d와 b로 연결된다. 또한 점 c와 e의 화살표는 각각 e와 c로 연결된다. 따라서 모든 화살표들의 길이 합은 3 + 3 + 2 + 3 + 2 = 13이다.


<그림 3>

점들의 위치와 색깔이 주어질 때, 모든 점에서 시작하는 화살표들의 길이 합을 출력하는 프로그램을 작성하시오.

- 시간 제한 : 2초
- 메모리 제한 : 512MB

접근 방법

이 문제를 해결하기 위해서는 같은 색깔의 점을들 서로 모을 필요가 있고 같은 색깔의 점들 사이의 최소 거리를 구하기 위해 위치별로 정렬을 할 필요가 있습니다. 그러므로 점을 나타낼 Point 클래스는 Comparable interface를 구현할 필요가 있습니다.

static class Point implements Comparable<Point> {
    int position;
    int color;

    Point(int position, int color) {
        this.position = position;
        this.color = color;
    }

    /**
     * @param other 정렬을 할 때 비교할 다른 점
     * @return this.color - other.color,
     * 둘의 색깔이 같다면 this.position - other.position
     */
    public int compareTo(Point other) {
        if (this.color == other.color) {
            return this.position - other.position;
        }

        return this.color - other.color;
    }
}

같은 색깔의 점들을 모으기 위해 compareTo에서 비교 조건에 색깔을 먼저 비교하고 색깔이 같으면 서로 위치를 오름차순으로 정렬이 되도록 해야합니다. 정렬 조건을 구현하였으니 이제 한 점의 이전 점과 다음 점의 거리 중 더 짧은 거리를 구하는 method를 구현하여야 합니다.

static class Point implements Comparable<Point> {
    int position;
    int color;

    ...

    /**
     * @param previous 이전 점
     * @param next 다음 점
     * @return 이전 점과 다음 점 중 더 가까운 길이
     */
    public int getShortestDistance(Point previous, Point next) {
        int leftDistance = this.getDistance(previous);
        int rightDistance = this.getDistance(next);

        // 이전 점과 거리를 구할 수 없는 경우
        if (leftDistance == 0) return rightDistance;

        // 다음 점과 거리를 구할 수 없는 경우
        if (rightDistance == 0) return leftDistance;

        // 두 점들의 거리 중 더 가까운 것을 반환
        return Integer.min(leftDistance, rightDistance);
    }

    /**
     * @param other 현재 점과 비교할 다른 점
     * @return 색깔이 같은 다른 점이 주어지면 거리를 반환, 그렇지 않으면 0을 반환
     */
    private int getDistance(Point other) {
        // 비교할 점이 없으면 0을 반환
        if (other == null) return 0;

        // 서로 색깔이 다르다면 0을 반환
        if (this.color != other.color) return 0;

        // 현재 점과 다른 점의 거리를 반환
        return Math.abs(this.position - other.position);
    }
}

getDistance는 현재 점과 다른 점의 거리를 구하는 method입니다. 만약 다른 점이 주어지지 않거나 서로 색깔이 다른 경우 거리를 구할 수 없으므로 0을 반환을 하게 되고, 서로 색깔이 같은 경우에는 두 점 사이의 거리를 반환하게 됩니다.
getShortestDistance는 이전 점과 다음 점을 받아서 getDistance를 이용하여 각각의 현재 점과의 거리를 구하여 더 짧은 거리를 반환하게 됩니다. 만약 leftDistancerightDistance중 유효하지 않은 거리가 있을 경우 유효한 거리를 반환하게 되고 둘 다 유효하지 않으면 0을 반환합니다.

이전 점과 다음 점의 중 더 짧은 거리를 구하는 method도 구현하였으니 아래와 같이 문제를 해결할 수 있습니다.

코드

import java.io.*;
import java.util.*;

public class Main {

    static int n;
    static Point[] points;
    static int total = 0;

    static class Point implements Comparable<Point> {
        int position;
        int color;

        Point(int position, int color) {
            this.position = position;
            this.color = color;
        }

        /**
         * @param other 정렬을 할 때 비교할 다른 점
         * @return this.color - other.color,
         * 둘의 색깔이 같다면 this.position - other.position
         */
        public int compareTo(Point other) {
            if (this.color == other.color) {
                return this.position - other.position;
            }

            return this.color - other.color;
        }

        /**
         * @param previous 이전 점
         * @param next 다음 점
         * @return 이전 점과 다음 점 중 더 가까운 길이
         */
        public int getShortestDistance(Point previous, Point next) {
            int leftDistance = this.getDistance(previous);
            int rightDistance = this.getDistance(next);

            // 이전 점과 거리를 구할 수 없는 경우
            if (leftDistance == 0) return rightDistance;

            // 다음 점과 거리를 구할 수 없는 경우
            if (rightDistance == 0) return leftDistance;

            // 두 점들의 거리 중 더 가까운 것을 반환
            return Integer.min(leftDistance, rightDistance);
        }

        /**
         * @param other 현재 점과 비교할 다른 점
         * @return 색깔이 같은 다른 점이 주어지면 거리를 반환, 그렇지 않으면 0을 반환
         */
        private int getDistance(Point other) {
            // 비교할 점이 없으면 0을 반환
            if (other == null) return 0;

            // 서로 색깔이 다르다면 0을 반환
            if (this.color != other.color) return 0;

            // 현재 점과 다른 점의 거리를 반환
            return Math.abs(this.position - other.position);
        }
    }

    public static void main (String[] args) {
        input();
        func();
        System.out.println(total);
    }

    static void input() {
        Scanner scanner = new Scanner(System.in);

        n = scanner.nextInt();
        points = new Point[n];

        for (int i = 0; i < n; ++i) {
            points[i] = new Point(
                    scanner.nextInt(),
                    scanner.nextInt()
            );
        }

        scanner.close();
    }

    static void func() {
        Arrays.sort(points);

        // 2개 미만의 점이 존재할 경우 화살표를 그릴 수 있는 
        // 경우가 존재하지 않으므로
        if (n < 2) return;
        
        // 가장 처음 점의 화살표 길이
        total += points[0].getShortestDistance(null, points[1]);

        // for 문을 이용하여 이전 점과 다음 점 중 더 가까운 점에 화살표를 그린다.
        for (int i = 1; i < n - 1; ++i) {
            total += points[i].getShortestDistance(points[i - 1], points[i + 1]);
        }

        // 마지막 점의 화살표 길이
        total += points[n - 1].getShortestDistance(points[n - 2], null);
    }
}
profile
Hola, Mundo

0개의 댓글