백준 1922번 : 네트워크 연결

1. 문제 설명 (1922)

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

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

2. 분류

3. 풀이

가장 처음 풀어본 MST 문제이다.

MST 를 생성하는 여러 알고리즘 중 대표적으로 Prim 알고리즘Kruskal 알고리즘 의 두 가지가 있지만, 이 문제에서는 정점 의 수가 N (1 <= N <= 1000), 간선 의 수가 M (1 <= M <= 100,000) 으로 비교적 작은 편에 속했기 때문에, Kruskal 알고리즘 이 복잡도 면으로 우위라고 생각되어 Kruskal 알고리즘으로 풀었다.

cost 순으로 정렬한 후, Prioirity Queue 를 활용하여 find 메소드를 통해 parent 를 탐색, 이후 parent가 다르면 union 을 통해 병합해 주었다. Priority Queue 가 빌 때까지 findunion 을 반복해주면 끝.

4. 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.*;
import java.io.*;
 
public class Q1922 {
    
    static PriorityQueue<Edge> pq;
    static int[] parent;
    static int answer = 0;
    
    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());
        pq = new PriorityQueue<>();
        parent = new int[N+1];
        for(int i = 1; i <= N; i++)
            parent[i] = i;
        
        for(int i = 0; i < M; i++) {
            String[] abc = br.readLine().split(" ");
            int a = Integer.parseInt(abc[0]);
            int b = Integer.parseInt(abc[1]);
            int c = Integer.parseInt(abc[2]);
            pq.add(new Edge(a, b, c));
        }
        
        kruskal();
        bw.write(answer+"");
        bw.flush();
        bw.close();
    }
    
    public static void kruskal() {
        while(!pq.isEmpty()) {
            Edge edge = pq.poll();
            int a = find(edge.start);
            int b = find(edge.end);
            
            if(a != b) {
                union(a, b);
                answer += edge.cost;
            }
        }
    }
    
    public static void union(int a, int b) {
        parent[a] = b;
    }
    
    public static int find(int a) {
        if(parent[a] == a)
            return a;
        else
            return parent[a] = find(parent[a]);
    }
    
    static class Edge implements Comparable<Edge> {
        int start, end, cost;
        
        Edge(int start, int end, int cost) {
            this.start = start;
            this.end = end;
            this.cost = cost;
        }
        
        @Override
        public int compareTo(Edge n) {
            return this.cost - n.cost;
        }
    }
    
}
cs


5. 결과

result image

632ms로 잘 작동한다. 다음엔 Prim의 알고리즘으로 풀이해봐야겠다.

댓글남기기