解题代码
#include<stdio.h>
#define MAXN 1000
#define ERROR -1
#define Infinite 65534
int dist[MAXN];
int N, M;
int G[MAXN][MAXN];
void Inicialization(void);
int CountTotally(void);
int FindTheWay(void);
int main()
{
scanf("%d %d", &N, &M);
Inicialization();
int total = CountTotally();
printf("%d", total);
return 0;
}
void Inicialization(void) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
G[i][j] = Infinite;
int v1, v2, w;
for (int i = 0; i < M; i++) {
scanf("%d %d %d", &v1, &v2, &w);
G[v1 - 1][v2 - 1] = G[v2 - 1][v1 - 1] = w;
}
for (int i = 0; i < N; i++)
dist[i] = Infinite;
}
int CountTotally(void) {
int total = 0;
int vcount = 0;
dist[0] = 0;
vcount++;
for (int i = 0; i < N; i++)
if (dist[i] && G[0][i] < dist[i])
dist[i] = G[0][i];
int v;
while (1) {
v = FindTheWay();
if (v == ERROR) break;
total += dist[v];
vcount++;
dist[v] = 0;
for (int i = 0; i < N; i++)
if (dist[i] && G[v][i] < dist[i])
dist[i] = G[v][i];
}
if (vcount != N) return ERROR;
return total;
}
int FindTheWay(void) {
int min=Infinite, index;
for(int i=0;i<N;i++)
if (dist[i] && dist[i] < min) {
min = dist[i];
index = i;
}
if (min == Infinite) return ERROR;
return index;
}
测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/82c8a44236e18dd4a43267206949d8dc.png)
问题整理
1.Prim算法,该类算法注意dist数组的含义,比如在搜索最短路径时,通过寻找dist不为零的且为最小的目标,来逐个收入新的结点。