-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path08-图7 公路村村通 Prim算法.c
90 lines (74 loc) · 1.56 KB
/
08-图7 公路村村通 Prim算法.c
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
88
89
90
#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 1000
#define INF 65535
int vertexNum;
int graph[MaxVertexNum][MaxVertexNum];
int dist[MaxVertexNum];
void buildGraph();
void initDist();
int findMinDist();
int prim();
int main()
{
buildGraph();
printf("%d", prim());
return 0;
}
void buildGraph()
{
int edgeNum, i, end1, end2, weight;
scanf("%d %d", &vertexNum, &edgeNum);
for (i = 0; i < edgeNum; ++i) {
scanf("%d %d %d", &end1, &end2, &weight);
graph[end1 - 1][end2 - 1] = weight;
graph[end2 - 1][end1 - 1] = weight;
}
}
void initDist()
{
int i;
for (i = 0; i < vertexNum; ++i) {
dist[i] = INF;
}
}
int findMinDist()
{
int minV, i, minDist = INF;
for (i = 0;i < vertexNum; ++i) {
if (dist[i] != 0 && dist[i] < minDist) {
minDist = dist[i];
minV = i;
}
}
if (minDist < INF)
return minV;
else return -1;
}
int prim()
{
int i, totalWeight, vCount, v;
initDist();
for (i = 0; i < vertexNum; ++i) {
if (graph[0][i])
dist[i] = graph[0][i];
}
totalWeight = 0; vCount = 0;
dist[0] = 0;
++vCount;
while (1) {
v = findMinDist();
if (v == -1)
break;
totalWeight += dist[v];
dist[v] = 0;
++vCount;
for (i = 0; i < vertexNum; ++i)
if (dist[i] != 0 && graph[v][i] && graph[v][i] < dist[i]) {
dist[i] = graph[v][i];
}
}
if (vCount < vertexNum)
totalWeight = -1;
return totalWeight;
}