[上下界网络流] SGU 194. Reactor Cooling

来源:互联网 发布:lumion是什么软件 编辑:程序博客网 时间:2024/05/16 12:05

194. Reactor Cooling

题意:

给一个无源汇上下界网络求一个可行流。

思路:

基本是模板题了,这个论文说的很清楚。
主要学习这种建图方法和思路。

#include<bits/stdc++.h>using namespace std;const int N = 5005;const int M = 130005;const int inf = ~0u>>2;struct eg{    int u, v, cap; //源点汇点流量    eg(){}    eg(int a, int b, int c){ u = a, v = b, cap = c; }}edg[M]; //边数开大int fir[N], nex[M], ecnt, s, t;void add(int a, int b, int c){    edg[ecnt] = eg(a, b, c);    nex[ecnt] = fir[a], fir[a] = ecnt++;    edg[ecnt] = eg(b, a, 0);    nex[ecnt] = fir[b], fir[b] = ecnt++;}int lev[N], q[M], top, tail;bool Bfs(int s, int t){    memset(lev, -1, sizeof(lev));    top = tail = 0;    lev[s] = 0; q[tail++] = s;    while( top < tail  ){        int u = q[top++];        if( u == t ) return 1;        for(int k = fir[u]; k != -1; k = nex[k]){            int v = edg[k].v;            if( edg[k].cap && lev[v] == -1){                lev[v] = lev[u] + 1;                q[tail++] = v;            }        }    }    return 0;}int Dfs(int s, int t, int low){    if( s == t ) return low;    int a = 0, res = 0;    for(int k = fir[s]; k != -1; k = nex[k]){        int v = edg[k].v;        if(edg[k].cap && lev[v] == lev[s] +1 ){            a = Dfs(v, t, min(low - res, edg[k].cap) );            edg[k].cap -= a;            edg[k^1].cap += a;            res += a;            if(res == low) return res;        }    }    if(res == 0) lev[s] = -1;    return res;}int Dinic(int s, int t){    int res = 0, minflow;    while( Bfs(s, t) ){        while( minflow = Dfs(s, t, inf) ) res += minflow;    }    return res;}int inflow[M], outflow[M];int ans[M];int main(){    ecnt = 0; memset(fir, -1, sizeof(fir));    int n, m;    scanf("%d%d", &n, &m);    for(int a, b, c, d, i = 1; i <= m; ++i){        scanf("%d%d%d%d", &a, &b, &c, &d);        ans[i] = c;        add(a, b, d-c);        inflow[b] += c;        outflow[a] += c;    }    s = 0, t = n+1;    for(int i = 1; i <= n; ++i){        int MM = inflow[i] - outflow[i];        if(MM > 0) add(s, i, MM), outflow[s] += MM;        else if(MM < 0) add(i, t, -MM), inflow[t] += -MM;    }    int maxflow = Dinic(s, t);    if(maxflow != outflow[s] || outflow[s] != inflow[t]) return 0*puts("NO");    puts("YES");    for(int i = 1; i <= m; ++i) printf("%d\n", ans[i] + edg[(i-1)<<1|1].cap);}
0 0
原创粉丝点击