POJ - 1251 Jungle Roads 最小生成树Kruskal算法(模板)

Kruskal算法比Prim更好写


#include<iostream>
#include<cstdio>
#include<algorithm>

#define maxn 110
#define maxm 10010  
using namespace std;

int n;//点的个数
int m;//边的个数
int uf[maxn];

struct edg
{
	int from;
	int to;
	int cost;
}e[maxm];

bool cmp(const edg &x, const edg &y) {
	return x.cost<y.cost;
}

void init()
{
	for (int i = 0; i < maxn; i++)uf[i] = i;
}

int find(int x) {
	if (x == uf[x])return x;
	return uf[x] = find(uf[x]);
}

int Union(int x, int y) {//合并两个集合(如果x,y在同一集合,返回0,否则返回1)  
	x = find(x), y = find(y);
	if (x != y) {
		uf[x] = y;
		return 1;
	}
	return 0;
}

int Kruskal(int n, int m) {//n个点,m条边  
	sort(e, e + m, cmp);//排序  
	int sum = 0;//最小生成树的权值和  
	for (int i = 0; i<m; i++) {//从小到大枚举边  
		int from = e[i].from, to = e[i].to, cost = e[i].cost;
		sum += cost*Union(from, to);
	}
	return sum;//返回权值和  
}

int main()
{
	while (scanf("%d",&n)!=EOF)
	{
		init();
		if (n == 0)break;
		m = 0;
		for (int i = 0; i < n - 1; i++)
		{
			char from[4],to[4];
			int times,cost;
			scanf("%s%d", &from, ×);
			while (times--)
			{
				scanf("%s%d", &to, &cost);
				e[m].cost = cost;
				e[m].from = from[0] - 'A';
				e[m++].to = to[0] - 'A';
			}
		}
		printf("%d\n", Kruskal(n, m));
	}

	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值