本地会T求调赏关注

P3376 【模板】网络最大流

xxr___ @ 2024-01-15 20:59:51

#include<bits/stdc++.h>
using namespace std;

#define poly vector
#define N 201
#define ll long long

const int inf=1e9;
int n,m;
ll graph[N][N],pre[N],fl[N];

ll bfs(int s,int t){
    memset(pre,-1,sizeof(pre));
    fl[s]=inf;
    pre[s]=0;
    queue<int> q;q.push(s);
    while(q.size()){
        int u=q.front();q.pop();
        if(u==t)break;
        for(int i=1;i<=n;i++){
            if(i!=s&&graph[u][i]>0&&pre[i]==-1){
                pre[i]=u;q.push(i);fl[i]=min(fl[i],graph[u][i]);
            } 
        }
    }
    if(pre[t]==-1)return -1;
    return fl[t];
}

ll Maxflow(int s,int t){
    ll Maxfl=0;
    while(1){
        ll flow=bfs(s,t);
        if(flow==-1)break;
        int cur=t;
        while(cur!=s){
            int fa=pre[cur];
            graph[fa][cur]-=flow;
            graph[cur][fa]+=flow;
            cur = fa;
        }
        Maxfl+=flow;
    }
    return Maxfl;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int s,t;
    cin>>n>>m>>s>>t;
    memset(graph,0,sizeof(graph));
    for(int i=0;i<m;i++){
        int u,v,w;
        cin>>u>>v>>w;
        graph[u][v]+=w;
    }
    cout<<Maxflow(s,t);
    return 0;
}

|