-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathMST.cpp
63 lines (53 loc) · 1.23 KB
/
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
/*
graphs > minimum spanning tree (MST)
difficulty: easy
date: 03/Jun/2020
by: @brpapa
*/
#include <bits/stdc++.h>
using namespace std;
struct UFDS {
vector<int> p; // p[i] = pai do item i
UFDS(int N) {
p.resize(N);
for (int i = 0; i < N; i++) p[i] = i;
}
int findSet(int i) {
if (p[i] == i) return i;
return p[i] = findSet(p[i]);
}
bool isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
void unionSet(int i, int j) {
int setI = findSet(i);
int setJ = findSet(j);
if (!isSameSet(setI, setJ)) p[setI] = setJ;
}
};
typedef long long ll;
struct Tedge {
int u, v; ll w;
Tedge() {}
Tedge(int u, int v, ll w) : u(u), v(v), w(w) {}
bool operator<(const Tedge& p) const { return w < p.w; }
};
int main() {
int V, E; cin >> V >> E;
vector<Tedge> edgeList(E);
for (Tedge &e : edgeList) {
int u, v; cin >> u >> v; u--; v--;
ll w; cin >> w;
e = Tedge(u, v, w);
}
UFDS uf(V);
sort(edgeList.begin(), edgeList.end());
ll ans = 0;
for (Tedge e: edgeList)
if (!uf.isSameSet(e.u, e.v)) {
uf.unionSet(e.u, e.v);
ans += e.w;
}
cout << ans << endl;
return 0;
}