蔡子经数据结构7.13.2

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
81
82
83
84
85
86
87

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

#define MAXINT 9999
#define MAXN 100
int mat[MAXN][MAXN];
int n,u;

void prim(int cost[][MAXN], int n, int u)
{
int sum = 0;
int lowcost[MAXN], min;
int closest[MAXN];
memset(lowcost, 0, sizeof lowcost);
memset(closest, 0, sizeof closest);
int i,j,k;
for(int i = 1; i <= n; ++i)
{
cost[i][i] = 0;
lowcost[i] = cost[u][i];
closest[i] = u;
}
for(i = 1; i < n; ++i)
{
min = MAXINT;
for(j = 1; j <= n; ++j)
{
if(lowcost[j] != 0 && lowcost[j] < min)
{
min = lowcost[j];
k = j;
}
}
// printf("%d\n",k);
sum += lowcost[k];
lowcost[k] = 0;
printf("%3d%3d%5d\n",closest[k],k,cost[closest[k]][k]);
for(j = 1; j <= n; ++j)
{
if(cost[k][j] != 0 && cost[k][j] < lowcost[j])
{
lowcost[j] = cost[k][j];
closest[j] = k;
}
}
}
printf("%d\n",sum);
}

int main()
{
int n,u;
scanf("%d %d",&n,&u);
int edge;
scanf("%d",&edge);
int x,y,v;
memset(mat, 0x3f, sizeof(mat));
for(int i = 0; i < edge; ++i)
{
scanf("%d %d %d",&x,&y,&v);
mat[x][y] = mat[y][x] = v;
}

// for(int i = 1; i <= n; ++i)
// {
// for(int j = 1; j <= n; ++j)
// printf("%d ",mat[i][j]);
// puts("");
// }

prim(mat,n,u);
}
/*
6 1
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
*/