P3376 【模板】网络最大流 当前弧优化

#include<bits/stdc++.h>?
#include<iostream>
#include<cstring>
#include<stack>
#include<stdio.h>
const int maxn = 1e4 + 10;
int head[maxn];
int dft[maxn];
int cur[maxn];
int tot;
int n, m, S, T;
using namespace std;
struct node{
    int to;
    int next;
    int w;
    node() {}
    node(int a, int b, int c) : to(a), next(b), w(c) {}
}edge[maxn * 2];
 
void edgeadd(int a, int b, int c){
    edge[tot] = node(b, head[a], c);
    head[a] = tot++;
    edge[tot] = node(a, head[b], 0);
    head[b] = tot++;
}
 
int bfs(int s, int e){
    memset(dft, 0, sizeof(dft));
    queue<int> q;
    q.push(s);
    dft[s] = 1;
    while(!q.empty()){
        int nw = q.front();
        q.pop();
        for(int i = head[nw]; i != -1; i = edge[i].next){
            int w = edge[i].w;
            int v = edge[i].to;
            if(w <= 0 || dft[v]) continue;
            dft[v] = dft[nw] + 1;
            q.push(v);
        }
    }
    return dft[e]; 
} 
 
int dfs(int s, int e, int f){
    if(s == e) return f;
    int ans = 0;
    for(int i = cur[s]; i != -1; i = edge[i].next){
        int v = edge[i].to;
        int w = edge[i].w;
        cur[s] = i;
        if(dft[v] != dft[s] + 1 || w <= 0)
            continue;
        int we = dfs(v, e, min(w, f - ans));//由于多次增广, 不能为f
        edge[i].w -= we;
        edge[i ^ 1].w += we;
        ans += we;
    }
    return ans;
}
void init(){
    memset(head, -1, sizeof(head));
    tot = 0;
}
 
int dinic(int s, int e){
    int cnt = 0;
    while(bfs(s, e)){
        for(int i = 1; i <= n; i++){
            cur[i] = head[i];
        } 
        cnt += dfs(s, e, 0x3f3f3f3f);
    }
    return cnt;
}
 
int main(){
    ios::sync_with_stdio(false);
    cin >> n >> m >> S >> T;
    init();
    for(int i = 1; i <= m; i++){
        int a, b, c;
        cin >> a >> b >> c;
        edgeadd(a, b , c);
    }
    cout << dinic(S, T) << endl;
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值