POJ 2560 Freckles

Description

In an episode of the Dick VanDyke show, little Richie connects the freckles on his Dad's back to form apicture of the Liberty Bell. Alas, one of the freckles turns out to be a scar,so his Ripley's engagement falls through.
Consider Dick's back to be a plane with freckles at various (x,y) locations.Your job is to tell Richie how to connect the dots so as to minimize the amountof ink used. Richie connects the dots by drawing straight lines between pairs,possibly lifting the pen between lines. When Richie is done there must be asequence of connected lines from any freckle to any other freckle.

Input

The first line contains 0 <n <= 100, the number of freckles on Dick's back. For each freckle, a linefollows; each following line contains two real numbers indicating the (x,y)coordinates of the freckle.

Output

Your program prints a singlereal number to two decimal places: the minimum total length of ink lines thatcan connect all the freckles.

Sample Input

3

1.0 1.0

2.0 2.0

2.0 4.0

Sample Output

3.41

题目简介:告诉n给点的坐标,求怎样使所有点连接起且切路径最短。输出路径。

方法:先处理一下,算出各点之间的距离。然后就是一个最小生成树了。

 

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>

struct node 
{
	double x ,y;
}num[110];

struct dd
{
	int s ,e;
	double dis;
}no[10010];

int p[110];
int n;
double sum;

double make_dis(int x, int y)
{
	return sqrt((num[x].x - num[y].x) * (num[x].x - num[y].x) + (num[x].y - num[y].y) * (num[x].y - num[y].y));
};

int cmp(const void *a, const void *b)
{
	struct dd *c ,*d;
	c = (struct dd*)a;
	d = (struct dd*)b;
	return c->dis > d->dis ? 1 : -1;
};

int root(int x)
{
    if(p[x]==x)
    {
        return x;
    }
   return p[x] = root(p[x]);
};

void Kruskal(int k)
{
    int i ,x ,y;
    sum = 0.0;
    for(i = 0;i < k;i++)
    {
		x = root(no[i].s);
		y = root(no[i].e);
		if(x!=y)
		{
			sum += no[i].dis;
			p[x] = y;
		}
    }
};

int main()
{
	int i ,j;
	while(scanf("%d",&n)!=EOF)
	{
		for(i = 1;i<=n;i++)
		{
			scanf("%lf%lf",&num[i].x,&num[i].y);
		}

		int k = 0;
		for(i = 1;i<n;i++)
		{
			for(j = i+1;j<=n;j++)
			{
				no[k].s = i;
				no[k].e = j;
				no[k++].dis = make_dis(i,j);
			}
		}

		qsort(no,k,sizeof(no[0]),cmp);
		for(i = 0;i<110;i++)
		{
			p[i] = i;
		}
		Kruskal(k);
		printf("%.2lf\n",sum);
	}
	return 0;
}


 

你可能感兴趣的:(POJ 2560 Freckles)