Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 26390 | Accepted: 10410 |
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 <stdio.h>
#include <algorithm>
#define V 101
#define E V * (V-1) / 2
using namespace std;
struct Edge{
int u;
int v;
int w;
};
Edge edge[E];
int f[V];
int rank[V];
int n;
bool cmp(Edge a,Edge b){
if( a.w < b.w) {
return true;
} else {
return false;
}
}
void makeSet(){
for(int i = 0; i < n; i++){
f[i] = i;
rank[i] = 0;
}
}
int findRoot(int x){
if(x == f[x]){
return x;
} else {
return f[x] = findRoot(f[x]);
}
}
void merge(int a,int b){
int ra = findRoot(a);
int rb = findRoot(b);
if(ra != rb) {
if(rank[ra] < rank[rb]){
f[ra] = rb;
} else {
f[rb] = ra;
if(rank[ra] == rank[rb]){
rank[ra]++;
}
}
}
}
int main()
{
while(scanf("%d",&n) != EOF){
int sum = 0;
int k = -1;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
int w;
scanf("%d",&w);
if( j > i){
k++;
edge[k].u = i;
edge[k].v = j;
edge[k].w = w;
}
}
}
//Kruskal
makeSet();
sort(edge,edge+k+1,cmp);
for(int i = 0; i <= k; i++){
int ru = findRoot(edge[i].u);
int rv = findRoot(edge[i].v);
if(ru != rv) {
sum += edge[i].w;
merge(edge[i].u,edge[i].v);
}
}
printf("%d\n",sum);
}
return 0;
}