您的位置:首页 > 其它

BZOJ 3390 Bad Cowtractors牛的报复

2016-04-25 22:47 399 查看
HAHAHA奶牛题。。。。最大生成树。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxv 2050
#define maxe 40050
using namespace std;
struct edge
{
int u,v,w;
}e[maxe];
int n,m,father[maxv],ans=0;
bool cmp(edge x,edge y)
{
return x.w>y.w;
}
int getfather(int x)
{
if (x!=father[x])
father[x]=getfather(father[x]);
return father[x];
}
void kruskal()
{
for (int i=1;i<=n;i++) father[i]=i;
sort(e+1,e+m+1,cmp);
for (int i=1;i<=m;i++)
{
int u=e[i].u,v=e[i].v,w=e[i].w;
int f1=getfather(u),f2=getfather(v);
if (f1!=f2) {father[f1]=f2;ans+=w;}
}
}
bool check()
{
for (int i=2;i<=n;i++)
{
if (getfather(i)!=getfather(i-1))
return false;
}
return true;
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
kruskal();
if (check()) printf("%d\n",ans);
else printf("-1\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: