您的位置:首页 > 其它

hdu-1162-Eddy's picture(克鲁斯卡尔求最小生成树)

2015-08-13 19:14 417 查看

Eddy's picture

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 8128 Accepted Submission(s): 4122



Problem Description
Eddy begins to like painting pictures recently ,he is sure of himself to become a painter.Every day Eddy draws pictures in his small room, and he usually puts out his newest pictures to let his friends appreciate. but the result it
can be imagined, the friends are not interested in his picture.Eddy feels very puzzled,in order to change all friends 's view to his technical of painting pictures ,so Eddy creates a problem for the his friends of you.

Problem descriptions as follows: Given you some coordinates pionts on a drawing paper, every point links with the ink with the straight line, causes all points finally to link in the same place. How many distants does your duty discover the shortest length
which the ink draws?



Input
The first line contains 0 < n <= 100, the number of point. For each point, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the point.

Input contains multiple test cases. Process to the end of file.



Output
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the points.



Sample Input
3
1.0 1.0
2.0 2.0
2.0 4.0




Sample Output
3.41


//hdu-1162-Eddy's picture(最小生成树)
//题目大意:在坐标纸上画 n 个点;给你各点的坐标 (x,y)求一条最短的长度把这些点都连起来;
//用克鲁斯卡尔解题,流程如下: 
//输入(x,y)——> 构图 ——> 克鲁斯卡尔 ——> 打印最短长度; 
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int n,per[120];
double x[120],y[120];
struct node{
	int start;
	int end;
	double len;
}ans[10010]; 
double length(int i,int j)
{
   return sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));	
}
double cmp(node x,node y)
{
	return x.len<y.len; 
}
void init()
{
	int i;
	for(i=1;i<=n;i++)
	 per[i]=i;
}
int find(int x)
{
	int r=x;
	while(r!=per[r])
	  r=per[r];
	return r;
}
bool link(int x,int y)
{
	int fx=find(x),fy=find(y);
	if(fx!=fy)
	{
		per[fx]=fy;
		return true;
	}
    return false;
}
int main()
{
	int i,j,k,a,b;
	double l,m;
	while(scanf("%d",&n)!=EOF)
	{
		init();
		memset(ans,0,sizeof(ans));
		for(i=1;i<=n;i++)
		  scanf("%lf%lf",&x[i],&y[i]);
		k=1;
		for(a=1;a<n;a++)
		{
		  for(b=a+1;b<=n;b++)
		  {
		  	ans[k].start=a;
		  	ans[k].end=b;
		  	ans[k].len=length(a,b);
		  	k++;
		  }
	    }
		l=0;
		sort(ans+1,ans+k,cmp);
	    for(i=1;i<=k;i++)
	    {
	    	if(link(ans[i].start,ans[i].end))
	    	  l+=ans[i].len;
		}
	printf("%.2f\n",l);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: