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

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值