观光奶牛 「二分答案 + SPFA判负环」

观光奶牛

题目描述:

n个点,m条边,每个点都有一个权值f[i],每条边都有一个权值val[i],求图中的一个环,使的环上“各个点的权值之和”除以“环上个各个边的权值之和”最大,输出这个最大值

思路:

考虑二分答案

假设当前二分的答案是mid,那至少存在一个环,使 ∑ f [ i ] ∑ v a l [ i ] > = m i d \frac{\sum{f[i]}}{\sum{val[i]}}>=mid val[i]f[i]>=mid成立,转换成 m i d ∗ ∑ v a l [ i ] − ∑ f [ i ] < = 0 mid * \sum{val[i]}-\sum{f[i]}<=0 midval[i]f[i]<=0,将边的权值转换成val[i]*mid - f[i],然后用SPFA判断是否存在负环即可

#include 
using namespace std;

#define endl '\n'
#define inf 0x3f3f3f3f
#define mod 1000000007
#define m_p(a,b) make_pair(a, b)
#define mem(a,b) memset((a),(b),sizeof(a))
#define io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)

typedef long long ll;
typedef pair <int,int> pii;

#define MAX 10000 + 50
int n, m, k;
int a, b;
double c;
int f[MAX];

int tot;
int head[MAX];
struct ran{
    int to, nex;
    double val;
}tr[MAX];
inline void add(int u, int v, double c){
    tr[++tot].to = v;
    tr[tot].val = c;
    tr[tot].nex = head[u];
    head[u] = tot;
}

double dis[MAX];
bool vis[MAX];
int num[MAX];
bool SPFA(double mid){
    mem(vis, 0);mem(num, 0);
    queue<int>q;q.push(0);dis[0] = 0;vis[0] = 1;
    for(int i = 1; i <= n; ++i){
        dis[i] = 10000000.0;
    }
    while (!q.empty()) {
        int u = q.front();q.pop();vis[u] = 0;
        for(int i = head[u]; i; i = tr[i].nex){
            int v = tr[i].to;
            if(dis[v] > dis[u] + tr[i].val * mid - f[v]){
                dis[v] = dis[u] + tr[i].val * mid - f[v];
                num[v] = num[u] + 1;
                if(num[v] >= n){
                    return true;
                }
                if(!vis[v]){
                    vis[v] = 1;
                    q.push(v);
                }
            }
        }
    }
    return false;
}

void work(){
    cin >> n >> m;
    for(int i = 1; i <= n; ++i)cin >> f[i];
    for(int i = 1; i <= m; ++i){
        cin >> a >> b >> c;
        add(a, b, c);
    }
    for(int i = 1; i <= n; ++i)add(0, i, 0);
    double l = 0, r = 1000.0;
    while (r - l >= 1e-6) {
        double mid = (l + r) / 2;
        if(SPFA(mid))l = mid;
        else r = mid;
    }
    printf("%.2f\n", l);
}


int main(){
    io;
    work();
    return 0;
}



你可能感兴趣的:(图论,算法,二分答案,SPFA,数据结构)