luogu 2868 观光奶牛

题目

给定一张L个点、P条边的有向图,每个点都有一个权值f[i],每条边都有一个权值t[i]。
求图中的一个环,使“环上各点的权值之和”除以“环上各边的权值之和”最大。
输出这个最大值。
输入格式
第一行包含两个整数L和P。
接下来L行每行一个整数,表示f[i]。
再接下来P行,每行三个整数a,b,t[i],表示点a和b之间存在一条边,边的权值为t[i]。
输出格式
输出一个数表示结果,保留两位小数。
输入样例:
5 7
30
10
10
5
10
1 2 3
2 3 2
3 4 5
3 5 2
4 5 5
5 1 3
5 2 2
输出样例:
6.00

题解

题意:
∑ v a l [ i ] e d g e [ i ] → m a x \sum \frac{val[i]}{edge[i]} \rightarrow max edge[i]val[i]max
假设当前答案为 x x x,如果答案可以更新,那么我们有 ∑ v a l [ i ] e d g e [ i ] ⩾ x → ∑ x ∗ e d g e [ i ] − v a l [ i ] ⩽ 0 \sum\frac{val[i]}{edge[i]}\geqslant x\rightarrow \sum x*edge[i] - val[i]\leqslant0 edge[i]val[i]xxedge[i]val[i]0

那么我们就可以建权值为 x ∗ e d g e [ i ] − v a l [ i ] x * edge[i] - val[i] xedge[i]val[i] 的边,来判断是否存在负环来更新答案

code

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 100;
const int maxm = 1e4 + 100;
const int eps = 1e-5;

template <typename T>
inline void read(T &s) {
    s = 0; 
    T w = 1, ch = getchar();
    while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
    while (isdigit(ch))  { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
    s *= w;
}

int n, m, tot;
int lin[maxn], nex[maxm], edge[maxm], ver[maxm], val[maxn], cnt[maxn];
bool vis[maxn];
double dis[maxn];

inline void add(int from, int to, int dis) {
    ver[++tot] = to;
    edge[tot] = dis;
    nex[tot] = lin[from];
    lin[from] = tot;
}

bool spfa(double ans) {
    queue <int> q;
    for (int i = 1; i <= n; ++i) {
        q.push(i);
        cnt[i] = 1;
        vis[i] = true;
        dis[i] = 0.0;
    }
    while (!q.empty()) {
        int u = q.front(); q.pop(); 
        vis[u] = false;
        for (int i = lin[u]; i; i = nex[i]) {
            int  v = ver[i];
            if (dis[v] > dis[u] + edge[i] * ans - (double)val[u]) {
                dis[v] = dis[u] + edge[i] * ans - (double)val[u];
                if (!vis[v]) {
                    vis[v] = true;
                    q.push(v);
                    cnt[v]++;
                    if (cnt[v] >= n) return true;
                }
            }
        }
    }
    return false;
}

int main() {
    read(n), read(m);
    for(int i = 1; i <= n; ++i) 
        read(val[i]);
    for (int i = 1; i <= m; ++i) {
        int x, y, z;
        read(x), read(y), read(z);
        add(x, y, z);
    }
    double l = 0, r = 1e5 + 1;
    for (int i = 1; i <= 100; ++i) {
        double mid = (l + r) / 2.0;
        if (spfa(mid)) l = mid;
        else r = mid;
    }
    printf("%.2lf", l * 1.0);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值