蔡子经数据结构7.13.1

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
78
79
80


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXN 100
typedef struct Edge
{
int u,v,w;
} Edge;
Edge edges[MAXN];
int fa[MAXN];

int getf(int x)
{
if(fa[x] == x)
return x;
return fa[x] = getf(fa[x]);
}

//我在这里没有防止退化
void merge(int u, int v)
{
u = getf(u);
v = getf(v);
if(u != v)
fa[v] = u;
}

void kruskal(Edge* edge, int n)
{
int u,v,w;
int f1,f2;
int sum = 0;
for(int i = 0; i < n; ++i)
{
u = edge[i].u;
v = edge[i].v;
w = edge[i].w;
f1 = getf(u);
f2 = getf(v);
if(f1 == f2) continue;
merge(f1, f2);
sum += w;
}
printf("----%d----\n",sum);
}

int cmp(const void *a, const void *b)
{
return ((Edge*)a)->w - ((Edge*)b)->w;
}

int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; ++i)
fa[i] = i;
for(int i = 0; i < n; ++i)
scanf("%d %d %d",&edges[i].u,&edges[i].v,&edges[i].w);
qsort(edges, n, sizeof(Edge), cmp);
for(int i = 0; i < n; ++i)
printf("%d\n",edges[i].w);
kruskal(edges, n);
}
/*
10
1 2 6
1 4 5
1 3 1
2 3 5
3 4 5
2 5 3
3 5 6
3 6 4
4 6 2
5 6 6
*/