传送门:http://poj.org/problem?id=1251
题目没怎么看懂,反正是最小生成树题,感觉挺好过的。
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<vector>
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
struct node{
int s,e;
int v;
node(int a,int b,int c):s(a),e(b),v(c){}
};
bool cmp(node a,node b)
{
return a.v<b.v;
}
vector<node> edge;
int pre[110];
int Find(int x)
{
int s;
for(s=x;pre[s]>=0;s=pre[s]);
while(s!=x)
{
int t=pre[x];
pre[x]=s;
x=t;
}
return s;
}
void join(int a,int b)
{
int fa=Find(a),fb=Find(b);
int sum=pre[fa]+pre[fb];
if(pre[fa]>pre[fb])
{
pre[fa]=fb;
pre[fb]=sum;
}
else{
pre[fb]=fa;
pre[fa]=sum;
}
}
int kruskal(int n)
{
int ans=0;
int i;
int cnt=0;
for(i=0;i<edge.size();i++)
{
if(Find(edge[i].s)!=Find(edge[i].e))
{
join(edge[i].s,edge[i].e);cnt++;
ans+=edge[i].v;
}
if(cnt==n-1)
break;
}
return ans;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF&&n)
{
edge.clear();
memset(pre,-1,sizeof(pre));
int i,j;
for(i=1;i<n;i++)
{
char op[2];
int num;
scanf("%s%d",op,&num);
while(num--){
char to[2];int vv;
scanf("%s%d",to,&vv);
edge.push_back(node(op[0]-'A',to[0]-'A',vv));
}
}
sort(edge.begin(),edge.end(),cmp);
printf("%d\n",kruskal(n));
}
return 0;
}