UVa 11090 Going in Cycle! BellmanFord 判负权环

题目大意:
给你一个由n个点,m条边组成的有向图,求图中最小环的平均长度。
分析:
根据最小环的条件,我们可以通过二分的方法来实现,对于每个当前二分出来的答案,要使得环上的每一条边的平均值小于当前答案,就等价于

w(i,j)|(i,j)E<midsize(E)

进一步可以推导出:
(w(i,j)|(i,j)Emid)<0

所以说,只要把每一条边的权值减去mid再判断新图中是否存在负权环即可。
代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 60;

struct Edge { int from, to; double dist; };
struct BellmanFord {
    int n, m;
    vector<Edge> edges;
    vector<int> G[maxn];
    bool inque[maxn];
    double dis[maxn];
    int pre[maxn], cnt[maxn];

    void init(int n) {
        this->n = n;
        for(int i=0; i<n; i++) G[i].clear();
        edges.clear();
    }
    void AddEdge(int from, int to, double dist) {
        edges.push_back((Edge){from, to, dist});
        m = edges.size();
        G[from].push_back(m-1);
    }
    bool negativeCycle() {
        queue<int> q;
        memset(cnt, 0, sizeof(cnt));
        memset(inque, false, sizeof(inque));

        for(int i=0; i<n; i++) dis[i] = 0, q.push(i), inque[i] = true;
        while(!q.empty()) {
            int u = q.front(); q.pop(); inque[u] = false;
            for(int i=0; i<(int)G[u].size(); i++) {
                Edge& e = edges[G[u][i]];

                if(dis[e.to] > dis[u] + e.dist) {
                    dis[e.to] = dis[u] + e.dist;
                    if(!inque[e.to]) {
                        q.push(e.to);
                        pre[e.to] = G[u][i];
                        inque[e.to] = true;
                        if(++cnt[e.to] > n) return true;
                    }
                }
            }
        }
        return false;
    }
}Bel;

bool check(double mid) {
    for(int i=0; i<Bel.m; i++) 
        Bel.edges[i].dist -= mid;
    bool res = Bel.negativeCycle();
    for(int i=0; i<Bel.m; i++) 
        Bel.edges[i].dist += mid;
    return res;
}
double binary_search(double L, double R) {
    while(R - L > 1e-5) {
        double M = L + (R-L)/2;
        if(check(M)) R = M; else L = M;
    }
    return L;
}
int Case, T, n, m, u, v, w;
int main() {
#ifndef ONLINE_JUDGE
    freopen("data.txt", "r", stdin);
    freopen("ans.txt", "w", stdout);
#endif
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d", &n, &m);

        Bel.init(n);
        double L = 0, R = 0;
        for(int i=0; i<m; i++) {
            scanf("%d%d%d", &u, &v, &w); 
            u--, v--, R = R < w ? w : R;
            Bel.AddEdge(u, v, w);
        }
        printf("Case #%d: ", ++Case);
        if(!check(R + 1)) { printf("No cycle found.\n"); continue; } 
        double ans = binary_search(L, R);
        printf("%.2f\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值