专题四 Problem A

来源:互联网 发布:网络盗刷信用卡能查到 编辑:程序博客网 时间:2024/05/21 05:43
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. <br><br>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.<br>
 

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.<br><br>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.<br>
 

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. <br>
 

Sample Input
30 990 692990 0 179692 179 011 2
 

Sample Output
179
 



思路:

还是一个最小生成树问题,在遍历树的结点的时候,如果两地之间的路已经修通,就令这个路径的权威0


ac代码:

  1. #include <iostream>  
  2. #include <algorithm>  
  3. using namespace std;  
  4. const int S=105;  
  5. struct node{  
  6.     int x,y,n;  
  7. }e[S*S];  
  8. int f[S*S],g[S][S];  
  9. inline bool cmp(const node&a, const node&b){  
  10.     return (a.n<b.n);  
  11. }  
  12. int getfather(int k){  
  13.     if (f[k]==k) return k;  
  14.     else {  
  15.         int tmp=getfather(f[k]);  
  16.         f[k]=tmp;  
  17.         return tmp;  
  18.     }  
  19. }  
  20. int main(){  
  21.     int i,j,k,n,size,x,y,sum=0;  
  22.     cin>>n;  
  23.     for (i=0;i<n*n;i++) f[i]=i;  
  24.   
  25.     for (i=0;i<n;i++)  
  26.         for (j=0;j<n;j++)  
  27.             cin>>g[i][j];  
  28.     cin>>k;  
  29.     for (i=0;i<k;i++){  
  30.         cin>>x>>y;  
  31.         x--;y--;  
  32.         g[x][y]=0;g[y][x]=0;  
  33.     }  
  34.   
  35.     for (i=0,k=0;i<n;i++)  
  36.         for (j=0;j<n;j++,k++){  
  37.             e[k].x=i,e[k].y=j,e[k].n=g[i][j];  
  38.         }  
  39.     sort(e,e+n*n,cmp);  
  40.   
  41.    // for (i=0;i<n*n;i++) cout<<e[i].x<<" , "<<e[i].y<<"  is  "<<e[i].n<<endl;  
  42.     for (k=0,i=0;k<n-1;i++){  
  43.         x=getfather(e[i].x),y=getfather(e[i].y);  
  44.         if (x!=y) {f[x]=y;sum+=e[i].n;k++;}  
  45.     }  
  46.     cout<<sum<<endl;  
  47.   
  48.     return 0;  


0 0
原创粉丝点击