Description
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
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
Sample Input
3 0 990 692 990 0 179 692 179 0 1 1 2
Sample Output
179
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
int a,b,dist;
}road[6000];
int c[109][109],f[109];
int cmp(const void *a,const void *b)
{
struct node *c,*d;
c=(struct node*)a;
d=(struct node*)b;
return c->dist-d->dist;
}
int find(int x)
{
if(f[x]==x)
return x;
return find(f[x]);
}
int main()
{
int n,i,j,k,q,a,b,sum,fa,fb;
while(scanf("%d",&n)!=EOF)
{
k=0;
for(i=1;i<=n;i++)
f[i]=i;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&c[i][j]);
if(c[i][j]!=0&&i>j)
{
road[k].a=i;
road[k].b=j;
road[k].dist=c[i][j];
k++;
}
}
scanf("%d",&q);
for(i=0;i<q;i++)
{
scanf("%d%d",&a,&b);
if(a<b)
{
int t;
t=a;
a=b;
b=t;
}
for(j=0;j<k;j++)
{
if(road[j].a==a&&road[j].b==b)
{
road[j].dist=0;
break;
}
}
}
qsort(road,k,sizeof(road[0]),cmp);
sum=0;
for(i=0;i<k;i++)
{
fa=find(road[i].a);
fb=find(road[i].b);
if(fa!=fb)
{
sum+=road[i].dist;
f[fa]=fb;
}
}
printf("%d\n",sum);
}
return 0;
}