Constructing Roads
Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 17187 Accepted Submission (s): 6526
Problem Descriptionthere is N villages, which is numbered from 1 to N, and we should build some roads such that every t Wo villages can connect to each of the other. We say 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 was a road between A and C, and C and B are connected.
We know that there be already some roads between some villages and your job is the build some roads such so all the Vil Lages is connect and the length of the roads built is minimum.
Inputthe first line is a integer n (3 <= N <=), 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 are the distance (the distance s Hould is an integer within [1, +]) between village I and village J.
Then there was an integer q (0 <= q <= n * (n + 1)/2). Then come Q lines, each line contains the integers a and B (1 <= a < b <= N), which means the road between Villag e A and village B has been built.
Outputyou should output a line contains an integer, which is the length of the "All the roads" to be built such Lages is connected, and this value is minimum.
Sample Input30 990 692990 0 179692 179 011 2
Sample Output179 Read for a long time to understand, the first three lines means that the first three-way village, the distance from the first three-way village, the smallest generation tree to write!
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 intper[ the],map[101][101];6 structnode7 {8 intb,e,w;9}s[10000];Ten BOOLCMP (node X,node y) One { A returnx.w<Y.W; - } - voidInit () the { - for(intI=1;i< the; i++) -per[i]=i; - } + - intFindintx) + { A while(x!=Per[x]) atx=Per[x]; - returnx; - } - - BOOLJoin (intXinty) - { in intfx=find (x); - intfy=find (y); to if(fx!=fy) + { -per[fx]=fy; the return true; * } $ return false;Panax Notoginseng } - intMain () the { + intn,i,n1,a,b,j; A while(SCANF ("%d", &n)! =EOF) the { + init (); - for(i=1; i<=n;i++) $ for(j=1; j<=n;j++) $scanf"%d",&map[i][j]); -scanf"%d",&N1); - for(i=0; i<n1;i++) the { -scanf"%d%d",&a,&b);Wuyimap[a][b]=0; the } - intk=0; Wu for(i=1; i<=n;i++) - { About for(j=i;j<=n;j++) $ { -s[k].b=i; -S[k].e=J; -s[k].w=Map[i][j]; Ak++; + } the } -Sort (s,s+k,cmp); $ intsum=0; the for(i=0; i<k;i++) the { the if(Join (S[I].B,S[I].E)) thesum+=S[I].W; - } inprintf"%d\n", sum); the } the return 0; About } the
Constructing roads--hdu1102