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.
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.
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 |
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
int bin[10001];
struct node {
int s,e,w;
} a[10000];
int sum;
int findx(int x) {
if(x!=bin[x])
bin[x]=findx(bin[x]);
return bin[x];
}
int cmp(node a,node b) {
return a.w<b.w;
}
int merge(int a,int b,int c) {
int fx=findx(a);
int fy=findx(b);
if(fx!=fy) {
bin[fx]=fy;
sum+=c;
}return sum;
}
int main() {
int t,i,j;
while(scanf("%d",&t)!=EOF) {
for(i=0; i<1000; i++) {
bin[i]=i;
}
int pos=0;
for(i=0; i<t; i++) {// 重点 : 看赋值
for(j=0; j<t; j++) {
int k;
scanf("%d",&k);
a[pos].s=i;
a[pos].e=j;
a[pos].w=k;
pos++;
}
}
int q;
scanf("%d",&q);
while(q--) {
int g,h;
scanf("%d %d",&g,&h);if(findx(g-1)!=findx(h-1)) {
bin[findx(g-1)]=findx(h-1);
}
}
sum=0;
sort(a,a+pos,cmp);
for(i=0; i<pos; i++) {
merge(a[i].s,a[i].e,a[i].w);
}
printf("%d\n",sum);
}
return 0;
}