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
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
Sample Output
179
解题思路:
要修公路,输入一个n,表示n个村庄。接着输入n*n的矩阵,然后输入一个q 接下来的q行
每行包含两个数a,b,表示a、b这条边联通,就是已经有公路不用修了,要让所有村庄联通在一起问:修路最小代价?
最小生成树的变形,有的村庄已经连接了,就直接把他们的权值赋为0,一样的做最小生成树,Prim算法。
代码如下:
1 #include<iostream> 2 #include<stdio.h> 3 #include<algorithm> 4 using namespace std; 5 6 int N; 7 int dis[1001][1001]; 8 bool vis[1001][1001]; 9 struct edge{ 10 int u; 11 int v; 12 int w; 13 }e[10005]; 14 int pre[1001]; 15 int find(int x) 16 { 17 return (x==pre[x])?x:pre[x] = find(pre[x]); 18 } 19 bool cmp(edge a , edge b) 20 { 21 return a.w<b.w; 22 } 23 int Q; 24 int main() 25 { 26 scanf("%d",&N); 27 for(int i = 1 ; i <= N;i++) 28 { 29 pre[i] = i; 30 } 31 for(int i = 1 ; i <= N ;i++) 32 { 33 for(int j = 1 ; j <= N ;j++) 34 { 35 scanf("%d",&dis[i][j]); 36 } 37 } 38 39 int x , y; 40 scanf("%d",&Q); 41 int edge_num = 0 ; 42 while(Q--) 43 { 44 scanf("%d%d",&x,&y); 45 dis[x][y] = 0; 46 dis[y][x] = 0; 47 } 48 for(int i = 1 ;i <= N ;i++) 49 { 50 for(int j = 1 ; j <= N; j++) 51 { 52 53 e[edge_num].u = i; 54 e[edge_num].v = j; 55 e[edge_num].w = dis[i][j]; 56 edge_num++; 57 } 58 } 59 60 sort(e,e+edge_num,cmp); 61 int u , v , w; 62 int fx ,fy; 63 int ans = 0; 64 for(int i = 0 ; i < edge_num ;i++) 65 { 66 u = e[i].u; 67 v = e[i].v; 68 w = e[i].w; 69 70 fx = find(u); 71 fy = find(v); 72 73 if(fx!=fy) 74 { 75 pre[fx] = fy; 76 ans += w; 77 }else 78 { 79 continue; 80 } 81 } 82 printf("%d\n",ans); 83 return 0; 84 }