-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal.cpp
More file actions
44 lines (38 loc) · 780 Bytes
/
kruskal.cpp
File metadata and controls
44 lines (38 loc) · 780 Bytes
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
const ll N = 1000;
ll par[N], sz[N];
struct edge {
int a, b;
ll wt;
};
bool comp(edge n1, edge n2) {
return n1.wt < n2.wt;
}
void init() {
for (ll i = 0; i < N; i++) {
par[i] = i;
sz[i] = 1;
}
}
ll root(ll x) {
return (x == par[x] ? x : (par[x] = root(par[x])));
}
void unionab(ll a, ll b) {
ll ra = root(a), rb = root(b);
if (ra == rb) return;
if (sz[ra] > sz[rb]) swap(ra, rb);
par[ra] = par[rb];
sz[rb] += sz[ra];
}
ll kruskal(vector < edge > elist) {
init();
sort(elist.begin(), elist.end(), comp);
ll cost = 0;
for (auto i: elist) {
if (root(i.a) != root(i.b)) {
//add edges only which doesn't form loop;
unionab(i.a, i.b);
cost += i.wt;
}
}
return cost;
}