HDU 1102 Constructing Roads(并查集)
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.
InputThe 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. 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.
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.
OutputYou 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 2Sample Output
179
1 #include<stdio.h> 2 #include<iostream> 3 #include<algorithm> 4 #include<string.h> 5 #include<queue> 6 #include<vector> 7 #include<string> 8 #define mem(a, b) memset(a, b, sizeof(a)) 9 #define N 105 10 #define MOD 11 #define MIN 12 #define MAX 13 using namespace std; 14 15 int pre[N]; 16 struct node{ 17 int x, y, w; 18 }road[10010]; 19 20 int fi(int x){ 21 return pre[x]==x?x:pre[x]=fi(pre[x]); 22 } 23 24 void uni(int x, int y){ 25 int fx=fi(x), fy=fi(y); 26 if(fx!=fy){ 27 pre[fx]=fy; 28 } 29 } 30 bool cmp(node a, node y){ 31 return a.w<y.w; 32 } 33 int main(){ 34 int n, q, a, b; 35 while(scanf("%d",&n)!=EOF){ 36 int cnt=0; 37 for(int i=1; i<=n; i++){ 38 pre[i]=i; 39 for(int j=1; j<=n; j++){ 40 scanf("%d",&a); 41 if(i<j){ 42 road[cnt].x=i; 43 road[cnt].y=j; 44 road[cnt++].w=a; 45 } 46 } 47 } 48 scanf("%d",&q); 49 for(int i=0; i<q; i++){ 50 scanf("%d%d",&a, &b); 51 uni(a, b); 52 } 53 int ans=0; 54 sort(road, road+cnt, cmp); 55 for(int i=0; i<cnt; i++){ 56 if(fi(road[i].x)!=fi(road[i].y)){ 57 ans+=road[i].w; 58 uni(road[i].x, road[i].y); 59 } 60 } 61 printf("%d\n",ans); 62 } 63 }
WA了好几次,我就想,我也没错啊,然后,好吧,多组测试
posted on 2019-05-30 13:42 甜甜圈不懂巧克力的苦 阅读(259) 评论(0) 编辑 收藏 举报