HDU 1162 最小生成树(只给出点的坐标自行建边)

Eddy’s picture
TimeLimit:1000MS MemoryLimit:32768KB
64-bit integer IO format:%I64d
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.
SampleInput
3
1.0 1.0
2.0 2.0
2.0 4.0
SampleOutput
3.41

题意:给你n个点的坐标,问将这个几个点相连的最小花费
思路:将每个点与点之间暴力建边然后跑最小生成树即可 主要是暴力建边的过程
下面献上我的low逼代码

#include 
#include 
#include 
#include 

using namespace std;

const int N = 100;

int fa[100005];

void init(int n)///并查集初始化
{
    for(int i = 1; i <=n; i++)
        fa[i] = i;
}

int findx(int a)
{
    return a == fa[a] ? a : fa[a] = findx(fa[a]);///递归寻找根节点
}

bool join(int a, int b)///合并
{
    a = findx(a);
    b = findx(b);
    if (a != b)
    {
        fa[a] = b;
        return true;
    }
    else
        return false;
}

struct node///存点坐标
{
    double x, y;
} a[N];

struct Edge///建边
{
    int u, v;
    double w;
} way[N * (N - 1)];

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

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        init(N);

        for(int i = 0; i < n; i++)
            scanf("%lf%lf", &a[i].x, &a[i].y);

        int cnt = 0;
        for(int i = 0; i < n; i++)///暴力建边
            for(int j = 0; j < n; j++)
                if(i < j)
                {
                    way[cnt].u = i + 1;
                    way[cnt].v = j + 1;
                    way[cnt++].w = 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));
                }

        double ans = 0;
        sort(way, way + cnt, cmp);///kruskal

        for(int i = 0; i < cnt; i++)
        {
            if(join(way[i].u, way[i].v))
                ans += way[i].w;
        }

        printf("%.2f\n", ans);
    }
    return 0;
}

你可能感兴趣的:(图论)