AcWing 361. 观光奶牛(二分+点权值变为边权值+判断正环)

思路

  • 题目要求一个环,满足sum(f[i])/sum(l[i])取最大值,f[i]为环上每个点的权值,l[i]为环上每个边的权值,这种一个数除以一个数取最大的,一般用二分,这题变一下形,sum(f[i])/sum(l[i])>=mid,变为sum(f[i])-sum(l[i])*mid>=0,mid为二分的最大值,这样可以把点的权值放在该点的出边上,因为这是在一个环上,所以经过一个点的环,该点的出边必然也在环上,所以可以这么做
  • 之后只要判断一下是否存在正环就可以了,即对于每一个mid判断是否存在sum(f[i])-sum(l[i])*mid>=0
  • 判断正环取最长路径即可

代码

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1010, M = 5010;

int n, m;
int wf[N];
int h[N], e[M], wt[M], ne[M], idx;
double dist[N];
int q[N], cnt[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, wt[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

bool check(double mid)
{
    memset(dist, 0, sizeof dist);
    memset(st, 0, sizeof st);
    memset(cnt, 0, sizeof cnt);

    int hh = 0, tt = 0;
    for (int i = 1; i <= n; i ++ )
    {
        q[tt ++ ] = i;
        st[i] = true;
    }

    while (hh != tt)
    {
        int t = q[hh ++ ];
        if (hh == N) hh = 0;
        st[t] = false;

        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] < dist[t] + wf[t] - mid * wt[i])//求最长路径
            {
                dist[j] = dist[t] + wf[t] - mid * wt[i];
                cnt[j] = cnt[t] + 1;
                if (cnt[j] >= n) return true;
                if (!st[j])
                {
                    q[tt ++ ] = j;
                    if (tt == N) tt = 0;
                    st[j] = true;
                }
            }
        }
    }

    return false;
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i ++ ) cin >> wf[i];

    memset(h, -1, sizeof h);
    for (int j = 0; j < m; j ++ )
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }

    double l = 0, r = 1e6;
    while (r - l > 1e-4)
    {
        double mid = (l + r) / 2;
        if (check(mid)) l = mid;
        else r = mid;
    }

    printf("%.2lf\n", l);

    return 0;
}

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页