hdu 3371 Connect the Cities 最小生成树
2015-08-16 16:55
447 查看
[code]#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; const int inf=1<<24; int n,m,k,a[25000+5],b[25000+5],c[25000+5]; int mp[1024][1024]; int p[1024]; int Find(int x) { if(p[x]==x) return x; else return p[x]=Find(p[x]); } void Union(int x,int y) { int fx=Find(x),fy=Find(y); if(fx!=fy) { if(fx<fy) p[fy]=fx; else p[fx]=fy; } } int main() { int _,i,j,t,p1,p2,lowcost[1024]; scanf("%d",&_); while(_--) { for(i=0; i<1024; i++) p[i]=i; scanf("%d%d%d",&n,&m,&k); for(i=0;i<=n;i++) for(j=0;j<=n;j++) mp[i][j]=inf; for(i=0; i<m; i++) scanf("%d%d%d",&a[i],&b[i],&c[i]); for(i=0; i<k; i++) { scanf("%d",&t); scanf("%d",&p1); for(j=1; j<t; j++) { scanf("%d",&p2); Union(p1,p2); } } for(i=0; i<m; i++) { p1=Find(a[i]); p2=Find(b[i]); if(p1==p2) continue; mp[p1][p2]=min(mp[p1][p2],c[i]); mp[p2][p1]=min(mp[p2][p1],c[i]); } int ans=0; for(i=2; i<=n; i++) { if(Find(i)!=i) continue; lowcost[i]=mp[1][i]; } lowcost[1]=-1; for(i=2; i<=n; i++) { if(Find(i)!=i) continue; int minx=inf; int v=-1; for(j=1; j<=n; j++) { if(Find(j)!=j) continue; if(lowcost[j]!=-1&&lowcost[j]<minx) { v=j; minx=lowcost[j]; } } if(v!=-1) { ans+=minx; lowcost[v]=-1; for(j=1; j<=n; j++) { if(Find(j)!=j) continue; if(mp[v][j]<lowcost[j]) lowcost[j]=mp[v][j]; } } } for(i=1; i<=n; i++) if(Find(i)==i&&lowcost[i]!=-1) break; if(i>n) printf("%d\n",ans); else printf("-1\n"); } return 0; }
相关文章推荐
- 不带头结点的头插法和尾插法
- hdu 1251 统计难题
- SQL触发器
- HDU 1212 Big Number(简单的大数取模)
- The C Programming Language第二版第一章习题(部分)
- HDU 4325-Flowers(线段树+离散化)
- codeforces 570 E. Pig and Palindromes (DP)
- 编写高质量代码改善C#程序的157个建议——建议52:及时释放资源
- hdu 3371 Connect the Cities 最小生成树
- dijkstra算法
- poj 1182
- Spring(Struts、Hibernate优势 + Spring IOC、AOP + Spring实际开发过程)
- 多线程同步之读者写者问题
- 内联(行级)元素不能设置margin-top
- codeforces 250 div2 A B C D
- (树状数组)多校训练7 Segment Game
- 插入排序-直接插入排序、希尔排序
- [转载]2060年软件工程师会像电报报务员那样过时?
- 【LeetCode】257 - Binary Tree Paths
- (1)java虚拟机概念和结构图