UVaLive 5713 秦始皇修路(O(n^2)预处理MST的maxcost数组)

题目:https://vjudge.net/contest/135978#overview
题意:

秦始皇要在n个城市之间修筑一条道路使得任意两个城市均可连通。有个道士可以用法力帮忙修一条路。秦始皇希望其他的道路总长B最短且用法术连接的两个城市的人口之和A尽量大,因此下令寻找一个A / B的最大方案。

分析:

比较套路的题目
枚举道士修的道路,然后如果可以直接计算出A/B就可以了
首先城市要连通,那么花费最小就是最小生成树
因为道士会修一条路u-v,所以在u-v的最小生成树路上最大花费的哪条路就不必修了
问题就转化成了如何快速的求出最小生成树上u-v的最大权maxcost[u][v]
预处理用O(n^2)的时间求出maxcost数组

代码:

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <stack>
using namespace std;
typedef pair<int,double>pid;
const int INF = 1e9 + 9;
const int mod = 1000007;
const int N = 1000 + 9;
int n, m, x[N], y[N], p[N];

int pa[N];
int findset(int x) {
    return pa[x] != x ? pa[x] = findset(pa[x]) : x;
}

struct Edge {
    int x, y;
    double d;
    bool operator < (const Edge& rhs) const {
        return d < rhs.d;
    }
};

Edge e[N*N];

double maxcost[N][N];
vector<int> nodes;
vector<pid>g[N];
void dfs(int u, int fa, double facost) {
    for(int i = 0; i < nodes.size(); i++) {
        int x = nodes[i];
        maxcost[u][x] = maxcost[x][u] = max(maxcost[x][fa], facost);
    }
    nodes.push_back(u);
    for(int i = 0; i < g[u].size(); i++) {
        int v =g[u][i].first;
        double w=g[u][i].second;
        if(v != fa) dfs(v, u, w);
    }
}

double MST() {
    m = 0;
    for(int i = 0; i < n; i++)
        for(int j = i+1; j < n; j++)
            e[m++] = (Edge) {
            i, j, sqrt((x[i]-x[j])*(x[i]-x[j]) + (y[i] - y[j])*(y[i] - y[j]))
        };
    sort(e, e+m);
    for(int i = 0; i < n; i++) {
        pa[i] = i;
        g[i].clear();
    }
    int cnt = 0;
    double ans = 0;
    for(int i = 0; i < m; i++) {
        int x = e[i].x, y = e[i].y, u = findset(x), v = findset(y);
        double d = e[i].d;
        if(u != v) {
            pa[u] = v;
            g[x].push_back(pid(y,d));
            g[y].push_back(pid(x,d));
            ans += d;
            if(++cnt == n-1) break;
        }
    }
    return ans;
}
int main() {
    int T;
    scanf("%d", &T);
    while(T--) {
        scanf("%d", &n);
        for(int i = 0; i < n; i++) scanf("%d%d%d", &x[i], &y[i], &p[i]);
        double tot = MST();
        memset(maxcost, 0, sizeof(maxcost));
        nodes.clear();
        dfs(0, -1, 0);
        double ans = -1;
        for(int i = 0; i < n; i++)
            for(int j = i+1; j < n; j++) {
                ans = max(ans, (p[i] + p[j]) / (tot - maxcost[i][j]));
            }
        printf("%.2lf\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值