Notas de algoritmo --- 10.5 --- B

Creo que esta pregunta es un poco problemática. Después de todo, no hay duda para una pasada

#include<stdio.h>
#include<algorithm>
#include<math.h> 
using namespace std;

struct Pos{
	double x,y;
}pos[110];

struct Edge{
	int x,y;
	double w;
}edge[110];

int n;
int father[110];

bool cmp(Edge a,Edge b){
	return a.w<b.w;
}

void init(){
	for(int i=0;i<n;i++){
		father[i]=i;
	}
}

int findFather(int x){
	int a=x;
	while(father[x]!=x){
		x=father[x];
	}
	while(a!=father[a]){
		int z=a;
		a=father[a];
		father[z]=x;
	}
	return x;
} 

double Kruskal(int n,int m){
	init();
	sort(edge,edge+m,cmp);
	int count=0;
	double ans=0;
	for(int i=0;i<m;i++){
		int fa=findFather(edge[i].x);
		int fb=findFather(edge[i].y);
		if(fa!=fb){
			ans+=edge[i].w;
			father[fa]=fb;
			count++;
			if(count==n-1)break;
		}
	}
	if(count==n-1)return ans;
	else return -1;
}
int main(){
	while(1){
		scanf("%d",&n);
		if(n==0)break;
		double a,b;
		for(int i=0;i<n;i++){
			scanf("%lf%lf",&a,&b);
			pos[i].x=a;
			pos[i].y=b;
		}
		int num=0;
		for(int i=0;i<n;i++){
			for(int j=i+1;j<n;j++){
				edge[num].x=i;
				edge[num].y=j;
				edge[num].w=sqrt((pos[i].x-pos[j].x)*(pos[i].x-pos[j].x)+(pos[i].y-pos[j].y)*(pos[i].y-pos[j].y));//printf("%d,%d,%.2lf\n",edge[num].x,edge[num].y,edge[num].w);
				num++;
			}
		}
		double res=Kruskal(n,n*(n-1)/2);
		printf("%.2lf\n",res);
	}
} 
30 artículos originales publicados · Me gusta1 · Visitas 389

Supongo que te gusta

Origin blog.csdn.net/weixin_46265246/article/details/105287732
Recomendado
Clasificación