-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskalMinimumSpanningTree.cpp
More file actions
46 lines (41 loc) · 957 Bytes
/
KruskalMinimumSpanningTree.cpp
File metadata and controls
46 lines (41 loc) · 957 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
45
46
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
typedef pair <int, int> PII;
vector < int > pare;
int par(int x) {
if(pare[x] == x) return x;
if(pare[x] == -1) {
pare[x] = x;
return pare[x];
}
pare[x] = par(pare[x]);
return pare[x];
}
int main () {
int n, m;
cin >> n >> m;
pare = vector < int > (n, -1);
int x, y, z;
priority_queue < pair < int, PII > > cua;
for (int i = 0; i < m; i++) {
cin >> x >> y >> z;
x--;
y--;
cua.push(make_pair(-z, make_pair(x, y)));
}
pair < int, PII > p;
int cont = n;
int cont2 = 0;
while (cont != 1 and not cua.empty()) {
p = cua.top();
cua.pop();
if (par(p.second.first) != par(p.second.second)) {
pare[par(p.second.first)] = pare[p.second.second];
cont--;
cont2+=p.first;
}
}
cout << -cont2 << endl;
}