HDU 1875 畅通工程再续 最小生成树

题目https://cn.vjudge.net/problem/HDU-1875

题意:平面坐标系上,C个点,坐标[0, 1000]整数,要求修路使之变成连通图,一条边费用等于长度*100,长度不在[10, 1000]范围内的边不能选择。求最小费用。

思路:二重循环计算两点距离建边,边长不符合[10, 1000]的边忽略,之后求最小生成树即可。

代码:C++

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <stack>
#include <cmath>
using namespace std;

const int maxn = 100 + 10;

struct Edge
{
    int from, to;
    double val;
    Edge(int from, int to, double val): from(from), to(to), val(val) {}
    bool operator < (const Edge &t) const
    {
        return val < t.val;
    }
};

typedef pair<int, int> pr;

int n;
vector<pr> vp;
vector<Edge> ve;

int fa[maxn];

int findset(int x)
{
    return fa[x] == x ? x : fa[x] = findset(fa[x]);
}

void unionset(int x, int y)
{
    int p1 = findset(x);
    int p2 = findset(y);
    if(p1 != p2)
    {
        fa[p1] = p2;
    }
}

int main()
{
    int T;
    cin >> T;
    while(T--)
    {
        ve.clear();
        vp.clear();
        scanf("%d", &n);
        for(int i = 0; i < n; i++)
        {
            fa[i] = i;
            int a, b;
            scanf("%d%d", &a, &b);
            vp.push_back(pr(a, b));
        }
        for(int i = 0; i < n; i++)
        {
            int xi = vp[i].first;
            int yi = vp[i].second;
            for(int j = i + 1; j < n; j++)
            {
                int xj = vp[j].first;
                int yj = vp[j].second;
                int d2 = abs(xi - xj)*abs(xi - xj) + abs(yi - yj)*abs(yi - yj);
                if(d2 >= 10 * 10 && d2 <= 1000 * 1000)
                {
                    ve.push_back(Edge(i, j, sqrt(d2)));
                }
            }
        }
        sort(ve.begin(), ve.end());
        int cnt = 0;
        double sum = 0;
        for(int i = 0; i < ve.size(); i++)
        {
            int a = ve[i].from;
            int b = ve[i].to;
            double v = ve[i].val;
            if(findset(a) != findset(b))
            {
                unionset(a, b);
                cnt++;
                sum += v * 100;
            }
        }
        if(cnt == n - 1)
        {
            printf("%.1f\n", sum);
        }
        else
        {
            printf("oh!\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Rewriter_huanying/article/details/88391182