码迷,mamicode.com
首页 > 其他好文 > 详细

loj116 有源汇有上下界最大流

时间:2017-12-24 20:10:57      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:flow   queue   printf   scan   min   sleep   dinic   push   div   

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
struct Edge{
    int too, nxt, val, lim;
}edge[60005];
int n, m, ss, tt, sss, ttt, hea[255], cnt, lev[255], uu, vv, ww, xx;
int maxFlow, tot;
const int oo=0x3f3f3f3f;
queue<int> d;
void add_edge(int fro, int too, int val, int lim){
    edge[cnt].nxt = hea[fro];
    edge[cnt].too = too;
    edge[cnt].val = val;
    edge[cnt].lim = lim;
    hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val, int lim){
    add_edge(fro, too, val-lim, lim);
    add_edge(too, fro, 0, lim);
    add_edge(sss, too, lim, lim);
    add_edge(too, sss, 0, lim);
    add_edge(fro, ttt, lim, lim);
    add_edge(ttt, fro, 0, lim);
}
bool bfs(int fro, int too){
    memset(lev, 0, sizeof(lev));
    lev[fro] = 1;
    d.push(fro);
    while(!d.empty()){
        int x=d.front();
        d.pop();
        for(int i=hea[x]; i!=-1; i=edge[i].nxt){
            int t=edge[i].too;
            if(!lev[t] && edge[i].val>0){
                lev[t] = lev[x] + 1;
                d.push(t);
            }
        }
    }
    return lev[too]!=0;
}
int dfs(int fro, int too, int lim){
    if(fro==too)    return lim;
    int addFlow=0;
    for(int i=hea[fro]; i!=-1 && addFlow<lim; i=edge[i].nxt){
        int t=edge[i].too;
        if(lev[t]==lev[fro]+1 && edge[i].val>0){
            int tmp=dfs(t, too, min(lim-addFlow, edge[i].val));
            edge[i].val -= tmp;
            edge[i^1].val += tmp;
            addFlow += tmp;
        }
    }
    return addFlow;
}
void dinic(int fro, int too){
    maxFlow = 0;
    while(bfs(fro, too))    maxFlow += dfs(fro, too, oo);
}
int main(){
    cin>>n>>m>>ss>>tt;
    memset(hea, -1, sizeof(hea));
    sss = 0; ttt = n + 1;
    for(int i=1; i<=m; i++){
        scanf("%d %d %d %d", &uu, &vv, &ww, &xx);
        addEdge(uu, vv, xx, ww);
        tot += ww;
    }
    addEdge(tt, ss, oo, 0);
    dinic(sss, ttt);
    if(maxFlow<tot) printf("please go home to sleep\n");
    else{
        dinic(ss, tt);
        cout<<maxFlow<<endl;
    }
    return 0;
}

loj116 有源汇有上下界最大流

标签:flow   queue   printf   scan   min   sleep   dinic   push   div   

原文地址:http://www.cnblogs.com/poorpool/p/8098821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!