UVA 10034 By ACReaper

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 15024;
int u[maxn];
int v[maxn];
double w[5 * maxn];
int r[5 * maxn];
int fa[maxn];
struct pos{
	double x,y;
};
pos A[maxn];

int cmp(const int a,const int b){
	return w[a] < w[b];
}

int find(int root){
	return root == fa[root]?root:find(fa[root]);
}

int main(){
			int tc;
			scanf("%d",&tc);
			for(int t = 1; t <= tc; t++){
				int n;
				scanf("%d",&n);
				for(int i = 1 ; i <= n; i++){
					scanf("%lf%lf",&A[i].x,&A[i].y);
				}
				memset(w,0,sizeof(w));
				int k = 1;
				for(int i = 1; i <= n; i++){//构建完全图 
					for(int j = i + 1;j <= n; j++){
							double d = sqrt((A[i].x - A[j].x) * (A[i].x - A[j].x) + (A[i].y - A[j].y) * (A[i].y - A[j].y));
							u[k] = i,v[k] = j,w[k++] = d;
					}
				}
				double ans = 0.0;
				int num_e = n * (n - 1) /2;
				for(int i = 1; i <= n; i++)
					fa[i] = i;
				
				for(int i = 1; i <= num_e; i++)
					r[i] = i;
				sort(r + 1,r + 1 + num_e,cmp);//
			
				for(int i = 1; i <= num_e;i++){
					int e = r[i];
					int x = find(u[e]);//找到起点
					int y = find(v[e]);
					if( x != y){
						fa[x] = y;
						ans += w[e];
					} 
				}
				printf("%s", t == 1? "" : "\n");
				printf("%.2lf\n",ans);
			}	
	
	return 0;
}


2013 05 07

By ACReaper

你可能感兴趣的:(UVA 10034 By ACReaper)