08-图7-公路村村通-编程题

08-图7-公路村村通-编程题

解题代码

#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;
}

测试结果

在这里插入图片描述

问题整理

1.Prim算法,该类算法注意dist数组的含义,比如在搜索最短路径时,通过寻找dist不为零的且为最小的目标,来逐个收入新的结点。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值