Watering the Fields(irrigation)
#include <cstdio> #include <algorithm> struct edge{ int f,t,w; } ed[5000000]; int pl,n,c,i,j,k,l,f[3000],x[3000],y[3000],t,ps,sum,t2; inline void addedge(int f,int t,int w){ ed[++pl].t=t; ed[pl].w=w; ed[pl].f=f; } inline int find(int x){ t=x; while(f[x]) x=f[x]; while(f[t]) t2=f[t],f[t]=x,t=t2; return x; } bool merge(int a,int b){ a=find(a),b=find(b); if(a==b) return false; f[a]=b; return true; } inline int dist(int x,int y){ return x*x+y*y; } bool cmp(edge a,edge b){ return a.w<b.w; } int main(){ scanf("%d%d",&n,&c); for(i=1;i<=n;++i){ scanf("%d%d",x+i,y+i); } t=0; for(i=1;i<n;++i){ for(j=i+1;j<=n;++j){ if((k=dist(x[i]-x[j],y[i]-y[j]))>=c){ addedge(i,j,k); } } } ++pl; std::sort(ed+1,ed+pl,cmp); ps=n-1; i=1; while(ps && i<pl){ if(merge(ed[i].f,ed[i].t)) --ps,sum+=ed[i].w; ++i; } if(ps) printf("-1\n"); else printf("%d\n", sum); return 0; }
这个kruskal不知为何丧心病狂地慢..膜拜WJZ大神只有100+ms...700+ms的蒟蒻给跪