Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 42267 | Accepted: 17261 |
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
Source
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>
#include <stack>
#define maxn 110
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 90001
#define PI 3.141592657
#define INF 1<<30
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
struct edge{
int s,e;
int dist;
}e[10000];
bool cmp(edge a,edge b)
{
return a.dist<b.dist;
}
int fa[maxn];
void init(int n){
for(int i=0;i<=n;i++)
fa[i]=i;
}
int findfa(int x){
if(fa[x]==x)return x;
return fa[x]=findfa(fa[x]);
}
void Union(int x,int y){
fa[x]=y;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
int t,d;
while(cin>>t){
init(t);
int k=0;
for(int i=1;i<=t;i++)
for(int j=1;j<=t;j++){
scanf("%d",&d);
if(i!=j){
k++;
e[k].s=i;
e[k].e=j;
e[k].dist=d;
}
}
sort(e+1,e+k+1,cmp);
ll sum=0;
for(int i=1;i<=k;i++){
int u=findfa(e[i].s);
int v=findfa(e[i].e);
if(u!=v){
sum+=e[i].dist;
Union(u,v);
}
}
printf("%I64d\n",sum);
}
return 0;
}