[백준] 2887. 행성 터널 - Java Solution

문제

  • https://www.acmicpc.net/problem/2887

Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int planetNumber = Integer.parseInt(br.readLine());

        List<int[]> xData = new ArrayList<>();
        List<int[]> yData = new ArrayList<>();
        List<int[]> zData = new ArrayList<>();

        for (int i = 1; i < planetNumber + 1; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            int z = Integer.parseInt(st.nextToken());

            xData.add(new int[] { x, i });
            yData.add(new int[] { y, i });
            zData.add(new int[] { z, i });
        }

        xData.sort((a, b) -> a[0] - b[0]);
        yData.sort((a, b) -> a[0] - b[0]);
        zData.sort((a, b) -> a[0] - b[0]);

        int[] parents = new int[planetNumber + 1];

        for (int i = 1; i < planetNumber + 1; i++) {
            parents[i] = i;
        }

        PriorityQueue<int[]> edges = new PriorityQueue<>((a, b) -> a[0] - b[0]);

        for (int i = 0; i < planetNumber - 1; i++) {
            edges.add(new int[] { xData.get(i + 1)[0] - xData.get(i)[0], xData.get(i)[1], xData.get(i + 1)[1] });
            edges.add(new int[] { yData.get(i + 1)[0] - yData.get(i)[0], yData.get(i)[1], yData.get(i + 1)[1] });
            edges.add(new int[] { zData.get(i + 1)[0] - zData.get(i)[0], zData.get(i)[1], zData.get(i + 1)[1] });
        }

        int answer = 0;

        int count = edges.size();
        while (count-- > 0) {
            int[] edge = edges.poll();
            int cost = edge[0];
            int from = edge[1];
            int to = edge[2];

            if (find(parents, from) != find(parents, to)) {
                union(parents, from, to);
                answer += cost;
            }
        }

        System.out.println(answer);

        br.close();
    }

    private static void union(int[] parents, int a, int b) {
        a = find(parents, a);
        b = find(parents, b);

        if (a != b) {
            parents[b] = a;
        }
    }

    private static int find(int[] parents, int target) {
        if (parents[target] == target) {
            return target;
        }

        return parents[target] = find(parents, parents[target]);
    }
}

Leave a comment