dinic求条

P3376 【模板】网络最大流

CC__DIAMOND @ 2024-12-04 14:56:03

如题tle on #10 #11 找不到错误。怀疑是建图挂了。

#include <bits/stdc++.h>
#define mp make_pair
#define eb emplace_back
#define ep emplace
using namespace std;
using ll=long long;
using pii=array<int,2>;
using pll=array<ll,2>;
int t;
namespace Solution {
    constexpr int N=210;
    constexpr int M=5010;
    constexpr ll inf=0x3f3f3f3f3f3f3f3f;
    int n,m,s,t;
    struct E {
        int to;
        ll w;
    } e[M*2];
    int tot;
    vector<int> graph[N];
    void add(int u,int v,ll w) {
        e[tot]={v,w};
        graph[u].push_back(tot);
        tot++;
    }

    int dis[N],now[N];
    bool bfs(int s) {
        memset(dis,0,sizeof(dis));
        memset(now,0,sizeof(now));
        queue<int> q;
        q.ep(s);
        dis[s]=1;
        while(!q.empty()) {
            int x=q.front();
            // cout<<x<<'\n';
            q.pop();
            for(int ed: graph[x]) {
                int to=e[ed].to;
                if(e[ed].w<=0) continue;
                if(dis[to]) continue;
                dis[to]=dis[x]+1;
                q.ep(to);
                if(to==t) return true;
            }
        }
        return false;
     }

     ll dfs(int x,ll curr) {
        if(x==t) return curr;
        ll res=0;
        for(int i=now[x];i<graph[x].size();++i) {
            int ed=graph[x][i];
            if(e[ed].w<=0) continue;
            if(dis[e[ed].to]!=dis[x]+1) continue;

            ll k=dfs(e[ed].to,min(curr,e[ed].w));
            if(!k) dis[k]=0;
            curr-=k;
            res+=k;
            e[ed].w-=k;
            e[ed^1].w+=k;
        }
        return res;
     }

    void solve() {
        cin>>n>>m>>s>>t;
        for(int i=1;i<=m;++i) {
            int u,v;
            ll w;
            cin>>u>>v>>w;
            add(u,v,w);
            add(v,u,0);
        }

        ll ans=0;
        while(bfs(s)) {
            ans+=dfs(s,inf);
        }
        cout<<ans<<'\n';
    }
}

int main() {
    // freopen("P3673_5.in","r",stdin);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T=1;
    // cin>>T;
    for(t=1;t<=T;++t) {
        Solution::solve();
    }
    return 0;
}

by ThySecret @ 2024-12-04 15:23:25

没有用弧优化


by cff_0102 @ 2024-12-04 15:57:16

楼上正解


by CC__DIAMOND @ 2024-12-04 22:12:41

卧槽我忘了写当前弧了多谢大佬


|