刚学网络流一秒,Dinic求助,73pts

P3376 【模板】网络最大流

appIe365 @ 2023-01-07 22:02:32

#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define int long long
using namespace std;
const int N = 205,M = 5005;
int n,m,s,t,tot = 1;
int flows[N],head[N],lv[N],cur[N];
struct node{
    int to,next,w;
}eg[M*2];
void adde(int a,int b,int w){
    eg[++tot] = {b,head[a],w},head[a] = tot;;
}
void add(int a, int b, int c)
{
    adde(a,b,c);
    adde(b,a,0);
}
bool bfs(){
    memset(lv,-1,sizeof lv);
    memcpy(cur,head,sizeof head);
    queue<int> q;
    lv[s] = 0;
    q.push(s);
    while(q.size()){
        int u = q.front();q.pop();
        for(int i = head[u];i;i = eg[i].next){
            int val = eg[i].w,y = eg[i].to;
            if(val > 0 && lv[y] == -1){
                lv[y] = lv[u] + 1;
                q.push(y);
            }
        }
    }
    return lv[t] != -1;
}
int dfs(int flow,int u){
    if(u == t) return flow;
    int lass = flow;
    for(int i = cur[u];i && lass;i = eg[i].next){
        cur[u] = i;
        int y = eg[i].to,val = eg[i].w;
        if(val > 0 && lv[y] == lv[u]+1){
            int c = dfs(min(val,flow),y);
            lass -= c;
            eg[i].w -= c;
            eg[i^1].w += c;
        }
    }
    return flow - lass;
}
int Dinic(){
    int ans = 0;
    while(bfs())
        ans += dfs(inf,s);
    return ans;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin >> n >> m >> s >> t;
    int u,v,w;
    for(int i = 1;i <= m;i ++){
        cin >> u >> v >> w;
        add(u,v,w);
    }
    cout << Dinic();
    return 0;
}

提交记录,#5,6,10 WA


by Avakos @ 2023-01-07 22:12:14

int c = dfs(min(val,flow),y);

这里c应该在剩余流量和容量里取最大,不是总流量


by Avakos @ 2023-01-07 22:12:48

@Avakos 口胡了是最小(


by appIe365 @ 2023-01-07 22:26:07

@Avakos 谢谢dalao


|