UVa 11478 Halum BellmanFord判负权环

来源:互联网 发布:模具分析软件 编辑:程序博客网 时间:2024/05/21 07:56

题目大意:
给定一个有向图, 每条边都有一个权值, 每次你可以选择一个点v和一个整数d, 使得所有以v为终点的边权值减少d, 以v为起点的边权值增加d, 要使得边权最小的的边尽量大且非负。
代码:

#include<bits/stdc++.h>using namespace std;const int maxn = 500 + 10; const int maxm = 2700 + 10;struct BellmanFrod {    int n, m;    bool in_q[maxn];    int dis[maxn], pre[maxn], cnt[maxn];    int Begin[maxn], W[maxm], To[maxm], Next[maxm], E;    void init(int n) {        this->n = n; E = 0;        memset(Begin, 0, sizeof(Begin));    }    void AddEdge(int from, int to, int dist) {        To[++E] = to;        Next[E] = Begin[from];        W[E] = dist;        Begin[from] = E;    }    bool negativeCycle() {        queue<int> q;        memset(cnt, 0, sizeof(cnt));        memset(in_q, false, sizeof(in_q));        for(int i=0; i<n; i++) dis[i] = 0, q.push(i);        while(!q.empty()) {            int u = q.front(); q.pop(); in_q[u] = false;            for(int i=Begin[u]; i; i=Next[i]) {                int v = To[i];                if(dis[v] > dis[u] + W[i]) {                    dis[v] = dis[u] + W[i];                    pre[v] = u;                    if(!in_q[v]) {                        in_q[v] = true;                        q.push(v);                        if(++cnt[v] > n) return true;                    }                }            }        }return false;    }}Bel;bool check(int mid) {    for(int i=1; i<=Bel.E; i++)        Bel.W[i] -= mid;    bool res = Bel.negativeCycle();    for(int i=1; i<=Bel.E; i++)        Bel.W[i] += mid;    return !res;}int n, m, u, v, w;int main() {#ifndef ONLINE_JUDGE    freopen("data.txt", "r", stdin);    freopen("ans.txt", "w", stdout);#endif    while(scanf("%d%d", &n, &m) == 2) {        Bel.init(n);        int L = 1, R = 0;        for(int i=0; i<m; i++) {            scanf("%d%d%d", &u, &v, &w); u--, v--;            Bel.AddEdge(u, v, w); R = max(R, w);        }        if(check(R+1)) puts("Infinite");        else if(!check(1)) puts("No Solution");        else {            int ans = 1;            while(L <= R) {                int M = L + (R-L) / 2;                if(check(M)) ans = M, L = M + 1; else R = M - 1;            }            printf("%d\n", ans);        }    }    return 0;}
0 0
原创粉丝点击