畅通工程再续 HDU - 1875(最小生成树)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Miranda_ymz/article/details/86593109

 畅通工程再续 HDU - 1875

 题意:中文题意不解释了

思路:还是模板题,只不过给你点,自己加边,要判断一下是否符合条件。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
//最小生成树 
const int maxn=100+10;//最大点数
const int maxm=maxn*maxn;
int a[maxn];
int f[maxn];//并查集使用
struct Edge{
	int u,v;
	double w;
	bool operator <(const Edge &u)const{
		return w<u.w;
	}
}edge[maxm];
struct node{
	int x,y;
}point[maxn];
double dis(node a,node b)
{
	return sqrt(1.0*(a.x-b.x)*(a.x-b.x)+1.0*(a.y-b.y)*(a.y-b.y));
}
int tot;
void addedge(int u,int v,double w)
{
	edge[tot].u=u;
	edge[tot].v=v;
	edge[tot++].w=w;
} 
int find(int x)
{
	if(f[x]==-1) return x;
	return f[x]=find(f[x]);
}
double kruskal(int n)
{
	memset(f,-1,sizeof(f));
	sort(edge,edge+tot);
	int cnt=0;
	double ans=0;
	for(int i=0;i<tot;i++)
	{
		int u=edge[i].u;
		int v=edge[i].v;
		double w=edge[i].w;
		int t1=find(u);
		int t2=find(v);
		if(t1!=t2)
		{
			ans+=w;
			f[t1]=t2;
			cnt++;
		}
		if(cnt==n-1) break;
	}
	if(cnt<n-1) return -1;
	else return ans; 
}
int main() 
{
	int t,n,a,b,w;
	scanf("%d",&t);
	while(t--)
	{
		tot=0;
		scanf("%d",&n);
		for(int i=0;i<n;i++)
		scanf("%d%d",&point[i].x,&point[i].y);
		for(int i=0;i<n;i++)
		for(int j=i+1;j<n;j++)
		{
			double len=dis(point[i],point[j]);
			if(len>=10&&len<=1000){	
				addedge(i,j,len);
				addedge(j,i,len);	
			}
			} 
		double ans=kruskal(n);
		if(ans==-1) printf("oh!\n");
		else printf("%.1f\n",ans*100.0);
	}
	return 0;
}
 

猜你喜欢

转载自blog.csdn.net/Miranda_ymz/article/details/86593109