-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathKruskal.cpp
61 lines (45 loc) · 973 Bytes
/
Kruskal.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
/*8<
@Title:
Kruskal
@Description:
Find the minimum spanning tree of a graph.
@Time:
$O(E \log E)$
>8*/
struct UFDS {
vector<int> ps, sz;
int components;
UFDS(int n)
: ps(n + 1), sz(n + 1, 1), components(n) {
iota(all(ps), 0);
}
int find_set(int x) {
return (x == ps[x]
? x
: (ps[x] = find_set(ps[x])));
}
bool same_set(int x, int y) {
return find_set(x) == find_set(y);
}
void union_set(int x, int y) {
x = find_set(x);
y = find_set(y);
if (x == y) return;
if (sz[x] < sz[y]) swap(x, y);
ps[y] = x;
sz[x] += sz[y];
components--;
}
};
vector<tuple<ll, int, int>> kruskal(
int n, vector<tuple<ll, int, int>> &edges) {
UFDS ufds(n);
vector<tuple<ll, int, int>> ans;
sort(all(edges));
for (auto [a, b, c] : edges) {
if (ufds.same_set(b, c)) continue;
ans.emplace_back(a, b, c);
ufds.union_set(b, c);
}
return ans;
}