[백준] 1647. 도시 분할 계획 - Java Solution

문제

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

Solution

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

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

        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        // index 0 : cost
        // index 1 : from
        // index 2 : to
        PriorityQueue<int[]> edges = new PriorityQueue<>((a, b) -> a[0] - b[0]);

        for (int i = 0; i < m; i++) {
            st = new StringTokenizer(br.readLine());
            int from = Integer.parseInt(st.nextToken());
            int to = Integer.parseInt(st.nextToken());
            int cost = Integer.parseInt(st.nextToken());

            edges.add(new int[] { cost, from, to });
        }

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

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

        int answer = 0;
        int loadCount = 0;

        while (loadCount < n - 2) {
            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;
                loadCount++;
            }
        }

        System.out.println(answer);

        br.close();
    }

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

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

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

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

Leave a comment