Bad Cowtractors
Description Bessie has been hired to build a cheap internet network among Farmer John's N (2 <= N <= 1,000) barns that are conveniently numbered 1..N. FJ has already done some surveying, and found M (1 <= M <= 20,000) possible connection routes between pairs of barns. Each possible connection route has an associated cost C (1 <= C <= 100,000). Farmer John wants to spend the least amount on connecting the network; he doesn't even want to pay Bessie. Input * Line 1: Two space-separated integers: N and M Output * Line 1: A single integer, containing the price of the most expensive tree connecting all the barns. If it is not possible to connect all the barns, output -1. Sample Input Sample Output Hint OUTPUT DETAILS: Source |
[Submit] [Go Back] [Status] [Discus
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 2005
#define maxm 2005*2005+5
using namespace std;
int father[maxn];
int n,m;
struct edge
{
int u,v,w;
edge(){}
edge(int u,int v,int w):u(u),v(v),w(w){}
bool operator<(const edge&rhs)
{
return w>rhs.w;
}
}edges[maxm];
int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}
int cnt;
void addedge(int u,int v,int w)
{
edges[cnt++]=edge(u,v,w);
}
int kru()
{
int sum=0;
int ans=0;
sort(edges,edges+cnt);
for(int i=0;i<cnt;i++)
{
int u=edges[i].u;
int v=edges[i].v;
if(find(u)!=find(v))
{father[find(u)]=find(v);
sum+=edges[i].w;
if(++ans>=n-1)
return sum;
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<=n;i++)
father[i]=i;
cnt=0;
int u,v,w;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&u,&v,&w);
addedge(u,v,w);
}
printf("%d\n",kru());
}
return 0;
}