Dinic

/***********************************************\
 |Author: YMC
 |Created Time: 2014/4/15 19:42:23
 |File Name: Dinic.cpp
 |Description: 
\***********************************************/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#define MAX_V 1005
using namespace std;
#define INF 10000000
struct edge{
    int to,cap,rev;
};
vector <edge> G[MAX_V];
int level[MAX_V];
int iter[MAX_V];//当前弧,之前用过的已经没用了
void add_edge(int from,int to,int cap){
    G[from].push_back((edge){to,cap,G[to].size()});
    G[to].push_back((edge){from,0,G[from].size()-1});
}
void bfs(int s){
    memset(level,-1,sizeof(level));
    queue<int> que;
    level[s] = 0;
    que.push(s);
    while(!que.empty()){
        int v = que.front();
        que.pop();
        for(int i=0;i<G[v].size();++i){
            edge &e = G[v][i];
            if(e.cap > 0 && level[e.to]<0){
                level[e.to] = level[v] + 1;
                que.push(e.to);
            }
        }
    }
}
int dfs(int v,int t,int f){
    if(v == t) return f;
    for(int &i = iter[v];i         edge &e = G[v][i];
        if(e.cap > 0 && level[v] < level[e.to]){
            int d = dfs(e.to,t,min(f,e.cap));
            if(d > 0){
                e.cap -= d;
                G[e.to][e.rev].cap += d;
                return d;
            }
        }  
    }
    return 0;        //千万注意不要漏了返回0,不然会无限循环。 
}

int max_flow(int s,int t){
    int flow = 0;
    for(;;){
        bfs(s);
        //cout<<"haha";
        if(level[t] < 0) return flow;
        memset(iter,0,sizeof(iter));
        int f;
        while((f = dfs(s,t,INF)) > 0){
            flow += f;
        }
    }
    return flow;
}
int main() {
    //freopen("input.txt","r",stdin); 
    int n;
    scanf("%d",&n);
    int from,to,cap;
    int s,t;
    while(n–){
        scanf("%d%d%d",&from,&to,&cap);
        add_edge(from,to,cap);
    }
    scanf("%d%d",&s,&t);
    printf("%d\n",max_flow(s,t));
    return 0;
}

/*
7
4 1 10
1 3 6
1 2 6
3 2 3
4 2 2
2 5 5
3 5 8
4 5
11
请按任意键继续. . .

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值