在昨天的实验室周六比赛的时候第一次看到这道题目,就看了一眼图就果断想放弃。直到最后里结束还有一个小时,发现实在无题可做,最后泽成大佬研究了几分钟竟然一A,后来问了吴挺成是什么类型的题目,竟然说是什么最小生成树,当时一脸懵逼,这tm是什么jb鬼东西...........一听名字就搞不来,但还是去问了一下题意(懒得看题目了),突然发现这和杭电的畅通类型的题目有点像啊!!
原谅我看了题解(脸红)
然后发现,这他妈不就是并查集嘛..........
一言不合上代码:
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
#define N 220
int n,m,cnt;
int ro[N];
struct Node
{
int from,to;
int v;
}node[N];
bool cmp(Node p1,Node p2)
{
return p1.v<p2.v;//排序
}
int finds(int x)//并查集的中心思想,往上找头
{
if(ro[x]!=x)
ro[x]=finds(ro[x]);
return ro[x];
}
int judge(int x,int y)//判断是否是共同的头,如果是,则这两条路不用连,反之连起
{
int xx=finds(x);
int yy=finds(y);
if(xx!=yy)
{
ro[yy]=xx;
return 1;
}
return 0;
}
int solve()
{
int i,j;
int ans=0;
for(i=0;i<=n;i++)
ro[i]=i;
for(i=0;i<cnt;i++)//具体实现
{
if(judge(node[i].from,node[i].to))
{
ans+=node[i].v;
}
}
return ans;
}
int main()
{
int i,j,k,w,a;
char s[6];
while(~scanf("%d",&n)&&n)
{
cnt=0;
for(i=0;i<n-1;i++)
{
scanf("%s %d",&s,&k);
a=s[0]-'A';
for(j=1;j<=k;j++)
{
scanf("%s %d",&s,&w); //把所有的联通的关系都放在结构体里
node[cnt].from=a;node[cnt].to=s[0]-'A';node[cnt].v=w;
cnt++;
}
}
sort(node,node+cnt,cmp);//按路程的长短排序是为了让之后的处理先考虑的短的路程,有点贪心的思想
int res=solve();
printf("%d\n",res);
}
return 0;
}