当前位置: 代码迷 >> 综合 >> 【最小生陈树】P2212 [USACO14MAR]Watering the Fields S
  详细解决方案

【最小生陈树】P2212 [USACO14MAR]Watering the Fields S

热度:81   发布时间:2024-02-05 08:15:35.0

大于等于c的建边,跑kruskal即可

 

#include<bits/stdc++.h>
using namespace std;
const int maxn=2005;
int n,c,tot;
int x[maxn],y[maxn],f[maxn];
struct edge
{int u,v,w;
}e[maxn*maxn];
bool cmp(edge aa ,edge bb)
{return aa.w<bb.w;
}
int find(int x)
{if(x==f[x]) return x;return f[x]=find(f[x]);
}
void kruskal()
{int ans=0,cnt=0;for(int i=1;i<=n;i++) f[i]=i;for(int i=1;i<=tot;i++){int fa=find(e[i].u);int fb=find(e[i].v);if(fa==fb) continue;f[fa]=f[fb];ans+=e[i].w;cnt++;if(cnt==n-1) break;}if(cnt==n-1) printf("%d\n",ans);else printf("-1\n");return;
}
int main()
{freopen("a.in","r",stdin);freopen("a.out","w",stdout);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=i+1;j<=n;j++){int dis=(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]);if(dis>=c) {e[++tot].u=i; e[tot].v=j; e[tot].w=dis;}}sort(e+1,e+tot+1,cmp);kruskal();return 0;
}

 

  相关解决方案