알고리즘

백준 10423번 전기가 부족해 (JAVA)

박카스마시며코딩 2021. 12. 30. 23:21

https://www.acmicpc.net/problem/10423

 

10423번: 전기가 부족해

첫째 줄에는 도시의 개수 N(1 ≤ N ≤ 1,000)과 설치 가능한 케이블의 수 M(1 ≤ M ≤ 100,000)개, 발전소의 개수 K(1 ≤ K ≤ N)개가 주어진다. 둘째 줄에는 발전소가 설치된 도시의 번호가 주어진다. 셋째

www.acmicpc.net

 

저는 쿠르스칼 방법으로 해당 문제를 해결하였습니다. 

전원 공급하는 노드들은 parent를 0으로 설정하여 모두 연결하였습니다. 전원을 공급하는 것들은 연결된 것으로 봐도 무방하기 때문에 이렇게 작성하였습니다.

 

package BOJ.MST;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_10423 {
    private static class Node{
        int start;
        int end;
        int weight;

        public Node(int start, int end, int weight) {
            this.start = start;
            this.end = end;
            this.weight = weight;
        }
    }
    static int findSet(int[] parent, int index){
        if(parent[index] == index) return index;
        else{
            return parent[index] = findSet(parent,parent[index]);
        }
    }
    static boolean union(int[] parent, int a, int b){
        int parentA = findSet(parent,a);
        int parentB = findSet(parent,b);
        if(parentA == parentB){
            return false;
        }else{
            parent[parentA] = parentB;
            return true;
        }
    }
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int m = stoi.apply(st.nextToken());
        int k = stoi.apply(st.nextToken());
        int[] parent = new int[n + 1];
        for(int i = 1 ; i <= n ; i++){
            parent[i] = i;
        }
        PriorityQueue<Node> pq = new PriorityQueue<>((o1,o2)->{
            return o1.weight - o2.weight;
        });
        st = new StringTokenizer(br.readLine()," ");
        for(int i = 0 ; i < k ; i++){
            int number = stoi.apply(st.nextToken());
            parent[number] = 0;
        }
        for(int i = 0 ; i < m ; i++){
            st = new StringTokenizer(br.readLine()," ");
            int start = stoi.apply(st.nextToken());
            int end = stoi.apply(st.nextToken());
            int weight = stoi.apply(st.nextToken());
            pq.offer(new Node(start,end,weight));
        }


        int result = 0;
        while(!pq.isEmpty()){
            Node now = pq.poll();
            if(union(parent,now.start,now.end)){
//                System.out.println(now.start+" "+now.end+" "+now.weight);
                result += now.weight;
            }
        }
        System.out.println(result);
    }

}