Constructing Roads-最小生成树(kruskal)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102
题目描述:
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.
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
3
0 990 692
990 0 179
692 179 0
1
1 2
Simple Output
179
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 6 struct node 7 { 8 int u,v,cost; 9 }a[10005]; 10 int pre[105]; 11 int fin(int x) 12 { 13 if(x==pre[x]) 14 { 15 return x; 16 } 17 else 18 { 19 return pre[x]=fin(pre[x]); 20 } 21 } 22 23 void join(int x,int y) 24 { 25 int t1=fin(x); 26 int t2=fin(y); 27 if(t1!=t2) 28 { 29 pre[t1]=t2; 30 } 31 } 32 33 bool cmp(node x,node y) 34 { 35 return x.cost<y.cost; 36 } 37 38 int main() 39 { 40 int n; 41 while(~scanf("%d",&n)) 42 { 43 for(int i=0;i<=n;i++) 44 { 45 pre[i]=i; 46 } 47 int num,cnt=0;; 48 for(int i=1;i<=n;i++) 49 { 50 for(int j=1;j<=n;j++) 51 { 52 scanf("%d",&num); 53 a[cnt].u=i; 54 a[cnt].v=j; 55 a[cnt].cost=num; 56 cnt++; 57 } 58 } 59 sort(a,a+cnt,cmp); 60 int sum1=0,sum=0;//此处算是一个小剪枝吧 61 int q; 62 scanf("%d",&q); 63 int c,d; 64 for(int i=0;i<q;i++) 65 { 66 scanf("%d%d",&c,&d); 67 if(fin(c)!=fin(d)) 68 { 69 join(c,d);//已经修好路的村庄链接成一个集合 70 sum1++; 71 } 72 } 73 for(int i=0;i<cnt;i++) 74 { 75 if(fin(a[i].u)!=fin(a[i].v)) 76 { 77 join(a[i].u,a[i].v); 78 sum+=a[i].cost; 79 sum1++; 80 } 81 if(sum1==n-1) 82 { 83 break; 84 } 85 } 86 printf("%d\n",sum); 87 } 88 return 0; 89 }