hdu 1031 最小生成树

hdu 1031
原题:http://acm.hdu.edu.cn/showproblem.php?pid=1301
思路:  最小生成树基础应用,输入用%s,不用考虑回车,使用优先队列。
 
 
  1. #include <iostream>
  2. #include<cstdio>
  3. #include<cstring>
  4. #include<queue>
  5. #include<cstdlib>
  6. #include<algorithm>
  7. using namespace std;
  8. const int N=5050;
  9. struct node
  10. {
  11. int a,b,w;
  12. friend bool operator< (node p1,node p2)
  13. {
  14. return p1.w>p2.w;
  15. }
  16. }e[N];
  17. priority_queue<node> S;
  18. int pre[N];
  19. void init(int m)
  20. {
  21. for(int i=0;i<=m;i++)
  22. pre[i]=i;
  23. }
  24. int Find(int x)
  25. {
  26. if(pre[x]!=x) pre[x]=Find(pre[x]);
  27. return pre[x];
  28. }
  29. int Join(node s)
  30. {
  31. int x=Find(s.a);
  32. int y=Find(s.b);
  33. if(x!=y)
  34. {
  35. pre[x]=y;
  36. return s.w;
  37. }
  38. return 0;
  39. }
  40. int Kruskal(int m,int n)
  41. {
  42. int ans=0;
  43. init(m);
  44. int i=1;
  45. while(!S.empty())
  46. {
  47. node s=S.top();
  48. S.pop();
  49. ans+=Join(s);
  50. }
  51. return ans;
  52. }
  53. int main() {
  54. int m,n,i,j,k;
  55. int c,d;
  56. while(scanf("%d",&n),n)
  57. {
  58. while(!S.empty()) S.pop();
  59. m=n*(n-1)>>1;
  60. char str1[5],str2[5];
  61. k=0;
  62. for(i=0;i<n-1;i++)
  63. {
  64. scanf("%s %d",str1,&d);
  65. for(j=0;j<d;j++)
  66. {
  67. scanf("%s %d",str2,&c);
  68. e[k].a=str1[0]-'A';
  69. e[k].b=str2[0]-'A';
  70. e[k].w=c;
  71. S.push(e[k++]);
  72. }
  73. }
  74. printf("%d\n",Kruskal(m,n));
  75. }
  76. return 0;
  77. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值