九度:1154<最小生成树>

http://ac.jobdu.com/problem.php?pid=1154


// 北大10机试
// 1154:Jungle Roads
// 
// WA:原因,初始化时为1~SIZE-1,而使用时ch-'A',是从0开始的。
// 但是,本地测试却与答案相同!所以,优点隐蔽。
// 所以初始化时,为0~SIZE-1时,就安全保险了。
// 还需要养成习惯,做到点的开始为1。除非规定了第一个点为0.

#include <stdio.h>
#include <algorithm>

#define SIZE 30
#define MAXSIZE 350

using namespace std;


struct Edge
{
	int a, b;
	int cost;
	bool operator < (const Edge& A) const{
		return cost < A.cost;
	}
};

int fa[SIZE];
Edge edge[MAXSIZE];

void Init()
{
	for(int i=0; i<SIZE; i++)//扩大初始化范围
	{
		fa[i]=i;
	}
}

int Getfa(int x)
{
	if(x == fa[x])
		return x;
	else
		fa[x]=Getfa(fa[x]);
	return fa[x];
}

int main()
{
#ifdef ONLINE_JUDGE
#else
	freopen("E:\\in.txt", "r", stdin);
	//freopen("E:\\out.txt", "w", stdout);
#endif


	int n;
	while(scanf("%d", &n) != EOF && n)
	{
		Init();
		int len=0;
		while(--n>0){
			char temp;
			getchar();
			scanf("%c", &temp);
			int k;
			scanf("%d", &k);
			while(k-->0)
			{
				char ch;
				scanf(" %c %d", &ch, &edge[len].cost);
				edge[len].b=ch-'A';
				edge[len].a=temp-'A';
				len++;
			}
		}//n-1 lines

		//printf("len:%d\n", len);
		sort(edge, edge+len);
		//for(int j=0;j<len;j++)
		//{
		//	printf("%c\t%c\t%d\n", edge[j].a+'A', edge[j].b+'A', edge[j].cost);
		//}
		int ans=0;
		for(int i=0;i<len;i++)
		{
			int x = Getfa(edge[i].a);
			int y = Getfa(edge[i].b);
			if( x!=y)
			{
				fa[x] = y;
				ans += edge[i].cost;
				//printf("-");
			}
		}
		printf("%d\n", ans);
	}

	return 0;

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值