Constructing Roads
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4922 Accepted Submission(s): 1764
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
179
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int f[109],map[109][109],mark[109][109];
struct node{
int a,b,dist,flag;
}road[10100];
int find(int x)
{
if(x==f[x])
return x;
return find(f[x]);
}
int cmp(const void *a,const void *b)
{
struct node *c,*d;
c=(struct node *)a;
d=(struct node *)b;
if(c->flag!=d->flag)
return d->flag-c->flag;
else
return c->dist-d->dist;
}
int main()
{
int n,i,j,k,q,a,b,sum;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
f[i]=i;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&map[i][j]);
memset(mark,0,sizeof(mark));
scanf("%d",&q);
for(i=0;i<q;i++)
{
scanf("%d%d",&a,&b);
mark[a][b]=mark[b][a]=1;
}
k=0;
for(i=1;i<=n;i++)//把矩阵中的数存到结构体中
for(j=1;j<=n;j++)
if(map[i][j]!=0)
{
road[k].a=i;
road[k].b=j;
road[k].dist=map[i][j];
road[k].flag=mark[i][j];
k++;
}
qsort(road,k,sizeof(road[0]),cmp);
sum=0;
for(i=0;i<k;i++)
{
if(find(road[i].a)!=find(road[i].b))
{
f[find(road[i].a)]=find(road[i].b);
if(road[i].flag==0)
sum+=road[i].dist;
}
}
printf("%d\n",sum);
}
return 0;
}