08-图7 公路村村通

#include <stdio.h>

#define MAXINT 0x7fffffff
#define Max 1001
int Graph[Max][Max];

int Prim(int N);
void DFS(int N, int i, int *Visited);

int main(int argc, char const *argv[])
{
	// freopen("test.txt", "r", stdin);
	int N, M;
	scanf("%d %d", &N, &M);
	for (int i = 1; i <= N; i++){
		for (int j = 1; j <= N; j++){
			Graph[i][j] = Graph[j][i] = MAXINT;
		}
	}
	for (int i = 1; i <= M; i++){
		int c1, c2, budget;
		scanf("%d %d %d", &c1, &c2, &budget);
		Graph[c1][c2] = Graph[c2][c1] = budget;
	}
	for (int i = 1; i <= N; i++)
		Visited[i] = 0;
	DFS(N, 1, Visited);
	int flag = 1;
	int Visited[N+1];
	for (int j = 1; j <= N; j++){
		if (Visited[j] == 0)
			flag = 0;
	}
	if (flag){
		int ans = Prim(N);
		printf("%d", ans);	
	}
	else
		printf("-1");
	return 0;
}

void DFS(int N, int i, int *Visited)
{
	Visited[i] = 1;
	for (int j = 1; j <= N; j++){
		if (Visited[j] == 0 && Graph[i][j] != MAXINT){
			DFS(N, j, Visited);
		}
	}
}

int Prim(int N)
{
	int MST[N+1], dist[N+1], count = 0, sum = 0;
	for (int i = 0; i <= N; i++)
		MST[i] = 0;
	for (int i = 1; i <= N; i++)
		dist[i] = Graph[1][i];
	dist[1] = 0;
	while(1){
		int mindist = MAXINT, v = -1;
		for (int i = 1; i <= N; i++){
			if (MST[i] == 0 && dist[i] < mindist){
				v = i;
				mindist = dist[i];
			}
		}
		if (v == -1)
			break;
		MST[v] = 1, dist[v] = 0;
		sum += mindist, count++;
		for (int i = 1; i <= N; i++){
			if (MST[i] == 0 && Graph[v][i] < dist[i])
				dist[i] = Graph[v][i];
		}
	}
	if (count < N)
		return -1;
	else
		return sum;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>