#最小生成树#[luogu 2872] [USACO07DEC]道路建设Building Roads

题目

https://www.luogu.org/problem/P2872


解题思路

暴力跑就可以了。

注意return 0&printf("%d",ans);


代码

#include
#include
#include
#define ll long long
using namespace std; 
struct node1{
	ll x,y; 
}a[1005];
struct node2{
	ll x,y,z; 
}b[2500005];
ll n,m,g,tot,f[1005]; double ans; 
ll cf(ll x){return x*x;}
bool cmp(node2 x,node2 y){return x.z<y.z;}
ll find(ll x){return f[x]==x?x:f[x]=find(f[x]);}
int main(){
	scanf("%lld%lld",&n,&m);   
	for(ll i=1;i<=n;i++) {
		f[i]=i; 
		scanf("%lld%lld",&a[i].x,&a[i].y); 
	}
	for(ll i=1;i<=n;i++)
	 for(ll j=i+1;j<=n;j++) 
	 if(i!=j) b[++tot]=(node2){i,j,(cf(a[i].x-a[j].x)+cf(a[i].y-a[j].y))}; 
	sort(b+1,b+tot+1,cmp); 
	
	for(ll i=1,x,y;i<=m;i++) {
		scanf("%lld%lld",&x,&y); 
		if (find(x)!=find(y)) f[find(x)]=find(y),g++; 
		
	}
	if (g==(n-1))  return 0&printf("%.2lf",ans);
	for(ll i=1;i<=tot;i++){
		ll x=find(b[i].x),y=find(b[i].y); 
		if (x!=y){
			g++; ans+=sqrt((double)b[i].z);  
			if (g==(n-1)) return 0&printf("%.2lf",ans);
			f[x]=y; 
		}
	}
}

你可能感兴趣的:(最小生成树)