Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 23011 | Accepted: 9068 |
Description
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
#include<stdio.h>
#include<stdlib.h>
#define M 109
struct node{
int a,b,dist;
}road[M*(M-1)/2+1];
int f[109];
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;
return c->dist-d->dist;
}
int main()
{
int i,j,k,n,map[109][109],fa,fb;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&map[i][j]);
for(i=1;i<=n;i++)
f[i]=i;
k=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(map[i][j]!=0&&i>j)
{
road[k].a=i;
road[k].b=j;
road[k].dist=map[i][j];
k++;
}
qsort(road,k,sizeof(road[0]),cmp);
int 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;
}