HDOJ 3371 Connect the Cities(最小生成树--prime 水)
2015-08-12 20:18
387 查看
Connect the Cities
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 13663 Accepted Submission(s): 3692
[align=left]Problem Description[/align]
In 2100, since the sea level rise, most of the cities disappear. Though some survived cities are still connected with others, but most of them become disconnected. The government wants to build some roads to connect all of these cities
again, but they don’t want to take too much money.
[align=left]Input[/align]
The first line contains the number of test cases.
Each test case starts with three integers: n, m and k. n (3 <= n <=500) stands for the number of survived cities, m (0 <= m <= 25000) stands for the number of roads you can choose to connect the cities and k (0 <= k <= 100) stands for the number of still connected
cities.
To make it easy, the cities are signed from 1 to n.
Then follow m lines, each contains three integers p, q and c (0 <= c <= 1000), means it takes c to connect p and q.
Then follow k lines, each line starts with an integer t (2 <= t <= n) stands for the number of this connected cities. Then t integers follow stands for the id of these cities.
[align=left]Output[/align]
For each case, output the least money you need to take, if it’s impossible, just output -1.
[align=left]Sample Input[/align]
1
6 4 3
1 4 2
2 6 1
2 3 5
3 4 33
2 1 2
2 1 3
3 4 5 6
[align=left]Sample Output[/align]
1
ac代码:
#include<stdio.h> #include<string.h> #include<math.h> #include<iostream> #include<algorithm> #define MAXN 10100 #define INF 0x7fffffff #define min(a,b) (a>b?b:a) #define max(a,b) (a>b?a:b) using namespace std; int pri[MAXN][MAXN]; int v[MAXN]; int d[MAXN]; int dis[MAXN]; int n; int sum; void prime() { int i,j,k; int min; memset(v,0,sizeof(v)); for(i=1;i<=n;i++) dis[i]=pri[1][i]; v[1]=1; sum=0; for(i=1;i<n;i++) { min=INF; for(j=1;j<=n;j++) { if(v[j]==0&&dis[j]<min) { min=dis[j]; k=j; } } if(min==INF) break; v[k]=1; sum+=min; for(j=1;j<=n;j++) { if(v[j]==0&&dis[j]>pri[k][j]) dis[j]=pri[k][j]; } } if(i!=n) sum=-1; } int main() { int i,j,a,b,c,m,s; int t,q,num,k; scanf("%d",&t); while(t--) { scanf("%d%d%d",&n,&m,&k); for(i=1;i<=n;i++) { pri[i][i]=0; for(j=i+1;j<=n;j++) pri[i][j]=pri[j][i]=INF; } for(i=0;i<m;i++) { scanf("%d%d%d",&a,&b,&c); if(pri[a][b]>c) pri[a][b]=pri[b][a]=c; } for(i=0;i<k;i++) { scanf("%d",&num); for(j=0;j<num;j++) { scanf("%d",&d[j]); } for(j=0;j<num;j++) for(q=j+1;q<num;q++) pri[d[q]][d[j]]=pri[d[j]][d[q]]=0; } prime(); printf("%d\n",sum); } return 0; }
相关文章推荐
- 搜索树
- DFS
- 分割字符串
- 罗将公布手机锤,我感到深深的内疚
- 关于CABAC熵编码一些问题的研究
- 轮舞前夕
- 2015/08/12/HTTPURL中GET和POST/HTTPClient中的GET和POST
- C#学习之While循环
- UITouch 摇晃手势启动器
- Balanced Binary Tree
- Java——StringBuffer
- Java心得12
- 四层和七层负载均衡的区别
- HDU 5373 The shortest problem
- linux桌面之菜单与文件关联简介
- [Leetcode] Add Two Numbers
- Android LayoutCast 初探
- python中的map、filter、reduce函数
- 客户端与服务器数据传输的两种方式
- eclipse里配置maven