HDU Problem b

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.<br>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?<br>
 

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. <br><br>Input contains multiple test cases. Process to the end of file.<br>
 

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. <br>
 

Sample Input
 
  
3
1.0 1.0
2.0 2.0
2.0 4.0
 

Sample Output
 
  
3.41
 

题目大意:

在直角坐标系中,给你n的点的坐标

问:将这些点全部连接的最短距离,

输入,第一行表示几个点,接下来每一行有点的x,y坐标(实数)

输出:保留两位小数,

思路:kruskal算法,

计算时最好都用double类型数据

code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=0xfffff;
struct point1//点
{
    double x,y;
} a[101];
struct point//kruskal所需的数据
{
    //point x,y;
    int x,y;
    double v;
} s[10001];
int f[10001];
double dis(point1 p,point1 q)//计算距离
{
    double xx=p.x-q.x;
    double yy=p.y-q.y;
    return sqrt(xx*xx+yy*yy);
}
int Find(int x)
{
    if(f[x]!=x)
        f[x]=Find(f[x]);
    return f[x];
}
void Union(int x,int y)
{
    int p=Find(x);
    int q=Find(y);
    if(p!=q)
        f[p]=q;
}
bool cmp(point p,point q)
{
    return p.v<q.v;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)//注意多组数据
    {
        int cnt=0;
        double ans=0;
        int k=0;
        for(int i=1; i<=n; ++i)
        {
            cin>>a[i].x>>a[i].y;
        }
        for(int i=1; i<=n; ++i)
        {
            for(int j=1; j<=n; ++j)
            {
                if(i!=j)
                {
                    s[++cnt].x=i;
                    s[cnt].y=j;
                    s[cnt].v=dis(a[i],a[j]);
                }
            }
        }
        sort(s+1,s+cnt+1,cmp);
        for(int i=1; i<=cnt; ++i)
            f[i]=i;
        for(int i=1; i<=cnt; ++i)
        {
            if(Find(s[i].x)!=Find(s[i].y))
            {
                Union(s[i].x,s[i].y);
                ans+=s[i].v;
                ++k;
            }
            //if(k==n-1)
                //break;
        }
        printf("%0.2lf\n",ans);
    }
}
//完美的代码








猜你喜欢

转载自blog.csdn.net/sdau_fangshifeng/article/details/80317228