-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path210222_BOJ_6497.cpp
More file actions
76 lines (54 loc) · 1 KB
/
Copy path210222_BOJ_6497.cpp
File metadata and controls
76 lines (54 loc) · 1 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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int m, n;
vector<pair<int, pair<int, int>>> v;
vector<int> group(200000, 0);
int total;
int find(int a) {
if (group[a] == a) return a;
else return group[a] = find(group[a]);
}
bool isSameGroup(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return true;
group[b] = a;
return false;
}
void kruskal() {
for (int i = 0; i < m; ++i)
group[i] = i;
int cnt = 0;
for (int i = 0; i < v.size(); ++i) {
int x = v[i].second.first;
int y = v[i].second.second;
if (!isSameGroup(x, y)) {
cnt++;
total -= v[i].first;
}
if (cnt == m - 1)
break;
}
cout << total << "\n";
total = 0;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
while (1) {
cin >> m >> n;
if (m == 0 && n == 0)
break;
v.clear();
for (int i = 0; i < n; ++i) {
int x, y, z; cin >> x >> y >> z;
v.push_back({ z, {x, y} });
total += z;
}
sort(v.begin(), v.end());
kruskal();
}
return 0;
}