Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

codingfarm

MST(Minimum Spanning Tree) & Kruskal 본문

Algorithm & Data structure/이론

MST(Minimum Spanning Tree) & Kruskal

scarecrow1992 2020. 9. 6. 14:20
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//https://www.acmicpc.net/problem/1197
 
#include<iostream>
#include<vector>
#include<algorithm>
 
using namespace std;
 
class Edge {
public:
    int from, to, weight;
 
    Edge(int from_, int to_, int weight_) : from(from_), to(to_), weight(weight_) {}
    Edge() : Edge(-1-1-1) {}
 
    bool operator <(const Edge& rhs)const {
        return weight < rhs.weight;
    }
 
};
 
vector<Edge> edges;
vector<int> union_set;
vector<int> union_level;
 
int UnionFind(int index) {
    if (union_set[index] != -1)
        return union_set[index] = UnionFind(union_set[index]);
    else
        return index;
}
 
void UnionMerge(int a, int b) {
    a = UnionFind(a);
    b = UnionFind(b);
 
    if (a == b)
        return;
 
    //a의 레벨이 b보다 항상 낮아야한다.
    //a를 b에 포함시켜야 한다.
 
    if (union_level[a] > union_level[b])
        swap(a, b);
 
    union_set[a] = b;
 
    if (union_level[a] == union_level[b])
        union_level[b]++;
}
 
//edges의 정보를 순회하면서 최소 신장 트리를 구한다.
int MST() {
    sort(edges.begin(), edges.end());
    int ret = 0;
    for (int i = 0; i < edges.size(); i++) {
        //간선의 시작점과 끝점의 root가 같으면 사이클을 형성하는것이다.
        int a, b;
        a = UnionFind(edges[i].from);
        b = UnionFind(edges[i].to);
 
        if (a == b)
            continue;
 
        //i번 간선은 최소 신장 트리에 포함 될 수 있다.
        ret += edges[i].weight;
        UnionMerge(edges[i].from, edges[i].to);
    }
 
    return ret;
}
 
 
int main(void) {
    int V, E;
    scanf("%d %d"&V, &E);
    int from, to, weight;
    union_set.assign(V, -1);
    union_level.assign(V, 1);
    for (int i = 0; i < E; i++) {
        scanf("%d %d %d"&from, &to, &weight);
        from--, to--;
        edges.push_back(Edge(from, to, weight));
    }
    
    int ret = MST();
    printf("%d\n", ret);
 
    return 0;
}
 
cs

'Algorithm & Data structure > 이론' 카테고리의 다른 글

Heap  (0) 2020.09.06
LCA(Lowest Common Ancestor)  (0) 2020.09.06
Union Find  (0) 2020.09.06
Merge Sort  (0) 2020.09.06
list(static allocation)  (0) 2020.09.06
Comments