hdu 1102 kruskal Constructing Roads

来源:互联网 发布:自学c语言能找到工作吗 编辑:程序博客网 时间:2024/06/06 04:56

Constructing Roads

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10628    Accepted Submission(s): 3952


Problem Description
There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected. 

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
 

Input
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
 

Output
You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum. 
 

Sample Input
30 990 692990 0 179692 179 011 2
 

Sample Output
179
 

Source
kicc
 

Recommend
Eddy


解题思路:搞了一下午啊!终于搞了出来,kruskal算法求最小生成树需要用到并查集的知识,也就是求同一条边上的点是否有公共的父节点,没有的话,把这条边加入到该树中,另外由于数据关于主对角线对称,只需要存(n*n-n)/2个元素,我就是错在这里的!伤心啊
还有一点就是用sort函数对结构体排序
模板:
int cmp(const node &a1,const node &a2){return a1.w < a2.w;}

代码:
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int n,m,q,set[105];struct node{int u,v,w;}edge[101*101];int cmp(const node &a1,const node &a2){return a1.w < a2.w;}int find(int x){while(set[x]!=x)x=set[x];return x; }void kruskal(){int sum=0,x,y;sort(edge+1,edge+(n*n-n)/2+1,cmp);//for(int i=1;i<=(n*n-n)/2;i++)//printf("_%d ",edge[i].w );//printf("\n"); for(int i=1;i<=(n*n-n)/2;i++){x=edge[i].u ;y=edge[i].v ;x=find(x);y=find(y);if(x!=y){set[x]=y;//printf("%d %d %d\n",edge[i].u ,edge[i].v ,edge[i].w );sum+=edge[i].w ;}}printf("%d\n",sum);}int main(){while(scanf("%d",&n)!=EOF){int cnt=1,cost;for(int i=1;i<=n;i++)for(int j=1;j<=n;j++){scanf("%d",&cost);if(i<j){edge[cnt].u = i;edge[cnt].v = j;edge[cnt].w = cost;cnt++;}}for(int i=1;i<=n;i++)set[i]=i;scanf("%d",&q);int v1,v2;for(int i=1;i<=q;i++){scanf("%d%d",&v1,&v2);v1=find(v1);v2=find(v2);set[v2]=v1;}kruskal();}return 0;} 



原创粉丝点击