0%

最小生成树模板

最小生成树模板

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
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 1000005;
struct Node {
int x, y, z;
} edge[N];

int par[N];

void init(int n) {
for (int i = 0; i <= n; i++) {
par[i] = i;
}
}

bool cmp(Node x, Node y) {
return x.z < y.z;
}

int find(int x) {
if (x == par[x]) return par[x];
else return par[x] = find(par[x]);
}

int tot, ans;

int main() {
int n, m;
while (~scanf("%d", &n)) {
if (n == 0)
break;
ans = 0;
m = n * (n - 1) / 2;
init(n);
for (int i = 1; i <= m; i++) {
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
edge[i].x = x;
edge[i].y = y;
edge[i].z = z;
}
std::sort(edge + 1, edge + 1 + m, cmp);

for (int i = 1; i <= m; i++) {
int x = find(edge[i].x);
int y = find(edge[i].y);
if (x == y) continue;

tot++;
par[x] = y;
ans += edge[i].z;
}
if (tot < n - 1);
//生成失败
else
printf("%d\n", ans);
}
return 0;
}