BZOJ 3479: [Usaco2014 Mar]Watering the Fields(最小生成树)
这个= =最近刷的都是水题啊QAQ
排除掉不可能的边然后就最小生成树就行了= =
CODE:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 2010
struct edges{
int x,y,c;
}edge[maxn*maxn];
int l,x[maxn],y[maxn],n,c,ans,sum,f[maxn];
bool cmp(edges x,edges y) {return x.c<y.c;}
int addedge(int x,int y,int c){
edge[++l]=(edges){x,y,c};
}
int fin(int x) {if (x!=f[x]) f[x]=fin(f[x]);return f[x];}
int main(){
scanf("%d%d",&n,&c);
for (int i=1;i<=n;i++) scanf("%d%d",x+i,y+i);
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
if ((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])>=c)
addedge(i,j,(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
sort(edge+1,edge+l+1,cmp);
for (int i=1;i<=n;i++) f[i]=i;
for (int i=1;i<=l;i++){
int x=fin(edge[i].x),y=fin(edge[i].y);
if (x!=y){ans+=edge[i].c;sum++;if (sum>=n) break;f[x]=y;}
}
if (sum==n-1) printf("%d",ans);
else printf("-1");
return 0;
}