hdu 1031
原题:http://acm.hdu.edu.cn/showproblem.php?pid=1301
思路: 最小生成树基础应用,输入用%s,不用考虑回车,使用优先队列。
- #include <iostream>
- #include<cstdio>
- #include<cstring>
- #include<queue>
- #include<cstdlib>
- #include<algorithm>
- using namespace std;
- const int N=5050;
- struct node
- {
- int a,b,w;
- friend bool operator< (node p1,node p2)
- {
- return p1.w>p2.w;
- }
- }e[N];
- priority_queue<node> S;
- int pre[N];
- void init(int m)
- {
- for(int i=0;i<=m;i++)
- pre[i]=i;
- }
- int Find(int x)
- {
- if(pre[x]!=x) pre[x]=Find(pre[x]);
- return pre[x];
- }
- int Join(node s)
- {
- int x=Find(s.a);
- int y=Find(s.b);
- if(x!=y)
- {
- pre[x]=y;
- return s.w;
- }
- return 0;
- }
- int Kruskal(int m,int n)
- {
- int ans=0;
- init(m);
- int i=1;
- while(!S.empty())
- {
- node s=S.top();
- S.pop();
- ans+=Join(s);
- }
- return ans;
- }
- int main() {
- int m,n,i,j,k;
- int c,d;
- while(scanf("%d",&n),n)
- {
- while(!S.empty()) S.pop();
- m=n*(n-1)>>1;
- char str1[5],str2[5];
- k=0;
- for(i=0;i<n-1;i++)
- {
- scanf("%s %d",str1,&d);
- for(j=0;j<d;j++)
- {
- scanf("%s %d",str2,&c);
- e[k].a=str1[0]-'A';
- e[k].b=str2[0]-'A';
- e[k].w=c;
- S.push(e[k++]);
- }
-
- }
- printf("%d\n",Kruskal(m,n));
-
- }
- return 0;
- }