代码改变世界

POJ 1251 Jungle Roads 最小生成树

2012-08-17 20:21  javaspring  阅读(156)  评论(0编辑  收藏  举报

来源:http://poj.org/problem?id=1251

题意:就是给出你图,然后求最小生成树的值即可。注意输入。

思路:完全裸的最小生成树,kruskal水之。好久不写最小生成树,仔细想了想,还是写了出来。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <vector>
using namespace std;

#define CLR(arr,val) memset(arr,val,sizeof(arr))
const int N = 32;
vector<int> vv[N];
int numedge,father[N];
struct edge{
	int leftp,rightp,value;
}ee[1000];
bool cmp(edge a,edge b){
	return a.value < b.value;
}
int find(int x){
	if(x == father[x])
		return father[x];
	return find(father[x]);
}
bool union_set(int lp,int rp){
	int flp = find(lp);
	int frp = find(rp);
	if(flp == frp){
	  return false;
	}
	else{
	  father[flp] = frp;
	  return true;
	}
}
int kruskal(){
	int sum = 0;
	for(int i = 0; i < numedge; ++i){
		int lp = ee[i].leftp;
		int rp = ee[i].rightp;
		if(union_set(lp,rp))
			sum += ee[i].value;
	}
	return sum;
}
int main(){
	//freopen("1.txt","r",stdin);
	int n;
	while(scanf("%d",&n)&&n){ 
		char ch;
		int num,x;
		numedge = 0;
		for(int i = 1; i < n; ++i){
		  cin >> ch;
		  scanf("%d",&num);
		  while(num--){
		    cin >> ch;
			scanf("%d",&x);
			int y = (int)(ch - 'A' + 1);
			ee[numedge].leftp = i;
			ee[numedge].rightp = y;
			ee[numedge].value = x;
			numedge++;
		  }
		}
		  sort(ee,ee+numedge,cmp);
		  for(int i = 1; i < N; ++i)
			  father[i] = i;
		  int ans = kruskal();
		  printf("%d\n",ans);
	}
	return 0;
}