-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkruskal.cpp
48 lines (43 loc) · 924 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
typedef tuple<int, int, int> edge;
struct dsu
{
vector<int> root, size;
dsu(int n)
{
size.resize(n + 1, 1);
root.resize(n + 1);
for (int i = 1; i < n; i++) root[i] = i;
}
int find(int u) { return root[u] == u ? u : root[u] = find(root[u]); }
bool join(int u, int v)
{
u = find(u);
v = find(v);
if (u == v) return false;
if (size[u] < size[v]) swap(u, v);
root[v] = u;
size[u] += size[v];
return true;
}
};
int main()
{
int n, m;
cin >> n >> m;
dsu ds(n);
vector<edge> edges(m);
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
edges[i] = {c, a, b};
}
sort(edges.begin(), edges.end());
ll ans = 0;
for (int i = 0; i < m; i++)
{
int a, b, c;
tie(c, a, b) = edges[i];
if (ds.join(a, b)) ans += c;
}
}