백준 1922 네트워크 연결

·2022년 8월 29일
0

문제

문제 설명

도현이는 컴퓨터와 컴퓨터를 모두 연결하는 네트워크를 구축하려 한다. 하지만 아쉽게도 허브가 있지 않아 컴퓨터와 컴퓨터를 직접 연결하여야 한다. 그런데 모두가 자료를 공유하기 위해서는 모든 컴퓨터가 연결이 되어 있어야 한다. (a와 b가 연결이 되어 있다는 말은 a에서 b로의 경로가 존재한다는 것을 의미한다. a에서 b를 연결하는 선이 있고, b와 c를 연결하는 선이 있으면 a와 c는 연결이 되어 있다.)

그런데 이왕이면 컴퓨터를 연결하는 비용을 최소로 하여야 컴퓨터를 연결하는 비용 외에 다른 곳에 돈을 더 쓸 수 있을 것이다. 이제 각 컴퓨터를 연결하는데 필요한 비용이 주어졌을 때 모든 컴퓨터를 연결하는데 필요한 최소비용을 출력하라. 모든 컴퓨터를 연결할 수 없는 경우는 없다.


Java

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

public class Main {
    public static int findUnion(int[] union, int x){
        if(union[x]!=x)
            union[x]=findUnion(union, union[x]);

        return union[x];
    }

    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());
        int m=Integer.parseInt(br.readLine());

        //우선순위 큐 선언, [노드 A, 노드 B, 비용]의 형태이고 비용을 기준으로 오름차순 정렬
        PriorityQueue<int[]> pq=new PriorityQueue<>(Comparator.comparingInt(o->o[2]));
        for(int i=0; i<m; i++){
            StringTokenizer st=new StringTokenizer(br.readLine());
            int start=Integer.parseInt(st.nextToken())-1;
            int end=Integer.parseInt(st.nextToken())-1;
            int cost=Integer.parseInt(st.nextToken());

            //노드 A와 노드 B가 같으면 무시
            if(start!=end)
                pq.add(new int[]{start, end, cost});
        }

        //Union 초기화
        int[] union=new int[n];
        for(int i=0; i<n; i++)
            union[i]=i;

        int count=0;
        int result=0;
        //간선의 갯수가 n-1이 될 때까지
        while(count<n-1){
            int[] ptr=pq.poll();
            int start=ptr[0];
            int end=ptr[1];
            int cost=ptr[2];

            int a=findUnion(union, start);
            int b=findUnion(union, end);

            //싸이클을 형성하지 않으면 간선 채택
            if(a!=b){
                count++;
                result+=cost;
                union[Math.max(a, b)]=Math.min(a, b);
            }
        }

        //출력
        bw.write(result+"\n");
        bw.flush();
    }
}

해결 과정

  1. Kruskal 알고리즘으로 해결했다. 두 정점이 같은 간선의 정보가 입력될 수도 있다고 해서 제외해줬다.

  2. 😁

profile
渽晛

0개의 댓글