-
Notifications
You must be signed in to change notification settings - Fork 697
/
Kruskal's MST.cpp
87 lines (73 loc) · 1.14 KB
/
Kruskal's MST.cpp
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
typedef struct data
{
int u, v, w, idx;
data() {}
data(int u, int v, int w, int idx) : u(u), v(v), w(w), idx(idx) {}
}edge;
int n, m;
int connected;
int root[N], sz[N];
vector<pair<int, int> > g[N];
data edges[N];
void init()
{
for(int i=1;i<=n;i++)
{
root[i]=i;
sz[i]=1;
}
connected=n;
}
int rt(int k)
{
while(k!=root[k])
{
root[k]=root[root[k]];
k=root[k];
}
return k;
}
void merge(int u, int v)
{
int rt1=rt(u);
int rt2=rt(v);
if(rt1==rt2)
return;
connected--;
if(sz[rt1]>sz[rt2])
swap(rt1, rt2);
sz[rt2]+=sz[rt1];
sz[rt1]=0;
root[rt1]=root[rt2];
}
void add_edge(int idx, int u, int v, int w)
{
g[u].push_back({v, w});
g[v].push_back({u, w});
edges[idx]=edge(u, v, w, idx);
}
bool comp(data &d1, data &d2)
{
return d1.w < d2.w;
}
int kruskalMST()
{
init();
int cost=0;
sort(edges+1, edges+m+1, comp);
for(int i=1;i<=m;i++)
{
int u=edges[i].u, v=edges[i].v, w=edges[i].w;
int rt1=rt(u), rt2=rt(v);
if(rt1==rt2)
continue;
else
{
cost+=w;
merge(rt1, rt2);
}
}
return cost;
}
//Problem 1 (Kruskal + Flow): https://codeforces.com/gym/101667 : Problem E
//Solution 1: http://p.ip.fi/HHLC