九度OJ 1154 Jungle Roads

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xp1994816/article/details/52434502
#include <stdio.h>
#include <algorithm>
using namespace std;

int Tree[27];
int findRoot(int x)
{
	if(Tree[x] == -1) return x;
	else{
		int tmp = findRoot(Tree[x]);
		Tree[x] = tmp;
		return tmp;
	}
}

struct Edge{				//边
	int a , b;
	int cost;
	int operator < (const Edge &A) const{
		return cost < A.cost;
	}
}edge[680];

int main()
{
	int n;
	while(scanf("%d",&n) != EOF && n != 0){
		char c[10] ;					
		int k;
		int size = 0;
		for(int i = 1 ; i < n ; ++i){
			scanf("%s%d",c,&k);		//用%c会读入回车符,直接用%s避免这个问题,下同。
			while(k--){
				char t_c[10] ; 
				int t_cost ;
				scanf("%s%d" , t_c,&t_cost);
				edge[size].a = c[0] - 'A';
				edge[size].b = t_c[0]-'A';
				edge[size].cost = t_cost;
				++size;
			}
		}

		sort(edge , edge + size );		//按边权值由小到大。

		for(int i = 0 ; i < n ; ++i){			
			Tree[i] = -1;
		}

		int ans = 0;
		for(int i = 0 ; i < size ; ++i){
			int a , b;
			a = findRoot(edge[i].a);
			b = findRoot(edge[i].b);
			if(a != b){
				Tree[a] = b;
				ans += edge[i].cost;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xp1994816/article/details/52434502
今日推荐