-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuva11631.cpp
More file actions
80 lines (72 loc) · 1.62 KB
/
uva11631.cpp
File metadata and controls
80 lines (72 loc) · 1.62 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* Rishikesh
* UVA 11631 Dark Roads
* Simple MST problem
*/
#include<iostream>
#include<string>
#include<sstream>
#include<map>
#include<set>
#include<stack>
#include<vector>
#include<algorithm>
#include<functional>
#include<numeric>
#include<cmath>
#include<queue>
using namespace std;
class UnionFind {
private:
vector<int> parent;
public:
UnionFind(int n) {
parent.resize(n);
iota(parent.begin(), parent.end(), 0);
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void un(int x, int y) {
int a = find(x);
int b = find(y);
if (a != b) {
parent[b] = a;
}
}
};
int main() {
#ifdef DEBUGUVA
freopen("test", "r", stdin);
cout << "This is a DEBUG\n";
#endif
int m, n;
while (cin >> m >> n, m != 0 or n != 0) {
vector<tuple<int, int, int>> road;
int oldcost = 0;
for (int i = 0; i < n; i ++) {
int t1, t2, t3;
cin >> t1 >> t2 >> t3;
oldcost += t3;
road.emplace_back(t3, t1, t2);
}
sort(road.begin(), road.end());
set<int> vertices;
int i = 0, newcost = 0, nroads = 0;
UnionFind uf(m);
while(nroads != m - 1) {
int d = get<0>(road[i]);
int x = get<1>(road[i]);
int y = get<2>(road[i]);
if (uf.find(x) != uf.find(y)) {
uf.un(x, y);
newcost += d;
nroads++;
}
i++;
}
cout << oldcost - newcost << endl;
}
}