32 pts Dinic 求助

P3376 【模板】网络最大流

SilverLi @ 2023-05-27 15:39:59

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define pi pair<int,int>
#define mk make_pair
#define pb push_back
#define v first
#define w second
const int N=1e5+5;
int n,m,s,t;
int dis[N];
struct edge {
    int v,w,nxt;
}g[N];
int cnt,h[N],newh[N];
inline void add(int u,int v,int w) {
    g[++cnt].v=v,g[cnt].w=w;
    g[cnt].nxt=h[u],h[u]=cnt;
}
inline bool bfs() {
    memset(dis,0,sizeof(dis));
    dis[s]=1;
    queue<int> q;
    q.push(s);
    while(!q.empty()) {
        int v=q.front();
        q.pop();
        newh[v]=h[v];
        for(int l=h[v];l;l=g[l].nxt) {
            edge i=g[l];
            if(dis[i.v]==0&&i.w)
                dis[i.v]=dis[v]+1,
                q.push(i.v);
        }
    }
    return (dis[t]>0);
}
int dfs(int u,int sum) {
    if(u==t)    return sum;
    int res=0;
    for(int l=newh[u];l;l=g[l].nxt) {
        edge &i=g[l];
        edge &rev=g[l^1];
        newh[u]=l;
        if(dis[i.v]==dis[u]+1&&i.w) {
            int k=dfs(i.v,min(i.w,sum-res));
            i.w-=k,rev.w+=k;
            res+=k;
            if(res>=sum)    break;
        }
    }
    return res;
}
signed main() {
    cin>>n>>m>>s>>t;
    while(m--) {
        int u,v,w;
        cin>>u>>v>>w;
        add(u,v,w),
        add(v,u,0);
    }
    int ans=0;
    while(bfs())   ans+=dfs(s,1e9);
    cout<<ans;
    return 0;
}

by gcx12012 @ 2023-05-27 15:51:35

cnt要从1开始


by SilverLi @ 2023-05-27 15:54:43

@gcx12012 thx


|