BZOJ 3390: [Usaco2004 Dec]Bad Cowtractors牛的报复(最大生成树)
这很明显就是最大生成树= =
CODE:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 1010
#define maxm 20010
struct edges{
int x,y,z;
}edge[maxm];
bool cmp(edges a,edges b){return (a.z>b.z);}
int f[maxn];
int fin(int x){if (f[x]!=x) f[x]=fin(f[x]);return f[x];}
int main(){
int n,m;
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) f[i]=i;
for (int i=1;i<=m;i++) scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].z);
sort(edge+1,edge+1+m,cmp);
int sum=0,ans=0;
for (int i=1;i<=m;i++){
int x=fin(edge[i].x),y=fin(edge[i].y);
if (x!=y) { f[x]=y;sum++;ans+=edge[i].z;if (sum==n-1) {printf("%d",ans);return 0;}}
}
printf("-1\n");
return 0;
}