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.
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.
3 0 990 692 990 0 179 692 179 0 1 1 2
有n个城市,给出每两个城市之间的距离,有m组城市已经相连,若要将所有城市相连输出最小的距离
#include<stdio.h> #include<iostream> #include<queue> #include<string.h> #include<algorithm> #include<map> #include<math.h> using namespace std; int a[10010]; int y; int fin(int k) { int r=k; while(r!=a[r]) { r=a[r]; } int j=k; while(j!=a[j]) { int u=a[j]; a[j]=r; j=u; } return r; } struct st { int a1,a2; int s; }; int mia(st r) { int i,j; i=fin(r.a1); j=fin(r.a2); if(i!=j) { a[i]=j; y+=r.s; } } int cmp(st a,st b) { return a.s<b.s; } st c[10001000]; int main() { int n; int m; int b[101][101]; while(~scanf("%d",&n)) {int t=0; y=0; int k=0; for(int i=1;i<=n;i++) { a[i]=i; for(int j=1;j<=n;j++) { scanf("%d",&b[i][j]); c[k].a1=i; c[k].a2=j; c[k].s=b[i][j]; k++; } } scanf("%d",&m); for(int i=0;i<m;i++) { int k1,k2; scanf("%d%d",&k1,&k2); k1=fin(k1),k2=fin(k2); if(k1!=k2) a[k2]=k1; } sort(c,c+k,cmp); for(int i=0;i<k;i++) { mia(c[i]); } printf("%d\n",y); } return 0; }