跳到正文

个人记录

Dinic 中的优化与坑点

tis00约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月14日
收录
2026年3月2日
更新
2026年11月13日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=205;
const int M=10005;
const ll INF=1e18;
int n,m,s,t;
int head[N],nxt[M],ver[M],cst[M],tot=1;
int d[N],cur[N];
queue<int> Q;
void add(int u,int v,int w){
	ver[++tot]=v,cst[tot]=w,nxt[tot]=head[u],head[u]=tot;
	ver[++tot]=u,cst[tot]=0,nxt[tot]=head[v],head[v]=tot;
}
bool bfs(){
	while(!Q.empty()) Q.pop();
	for(int i=1;i<=n;i++) d[i]=0;
	d[s]=1;Q.push(s),cur[s]=head[s];
	while(!Q.empty()){
		int u=Q.front();Q.pop();
		for(int i=head[u];i;i=nxt[i]){
			int v=ver[i],w=cst[i];
			if(w&&!d[v]){
				d[v]=d[u]+1,cur[v]=head[v];
				if(v==t) return 1;
				Q.push(v);
			}
		}
	} 
	return 0;
} 
ll dinic(int u,ll flow){
	if(u==t) return flow;
	ll rest=flow;
	for(int i=cur[u];i&&rest;i=nxt[i]){
		cur[u]=i;
		int v=ver[i],w=cst[i];
		if(w&&d[v]==d[u]+1){
			ll k=dinic(v,min(rest,(ll)w));
			if(!k) d[v]=0;
			cst[i]-=k,cst[i^1]+=k;
			rest-=k;
		}
	}
	return flow-rest;
}
signed main(){
	scanf("%d%d%d%d",&n,&m,&s,&t);
	while(m--){
		int u,v,w;scanf("%d%d%d",&u,&v,&w);
		add(u,v,w);
	}
	ll flow=0,maxflow=0;
	while(bfs()) while(flow=dinic(s,INF)) maxflow+=flow;
	printf("%lld\n",maxflow);
	return 0;
}

优化一:bfs 时,走到终点就 break。

坑点:记得清空队列 Q。

优化二:当前弧优化。

坑点:应为 cur[u]=i 而非 cur[u]=nxt[i]。

原因:若执行 dinic(v) 后 rest>0 则当 rest 更大时,从 v 出发的流量也不会增多;反之,若执行 dinic(v) 后 rest=0 则说明当 rest 更大时,从 v 出发可能产生更多流量,若令 cur[u]=nxt[i] 则无法增多。

坑点:bfs 时记得重新令 cur[u]=head[u]。

优化三:rest=0 时就 break。

优化四:dinic(v)=0 就令 d[v]=0。

原因类优化二。

大坑:if(w&&d[v]==d[u]+1) 中一定要判 w>0,否则可能使 dinic(v) 时 flow=0,导致误认为从 v 出发不能产生流量。

原文