问题描述
给定 n n n 个点, m m m 条有向边,给定每条边的容量,求从点 s s s 到点 t t t 的最大流。
推荐博客
反向边作用
b
f
s
bfs
bfs分层优化-Dinic
网络流其他更强优化
算法思路
反向边的反悔作用:
以上为
F
F
FF
FF 算法,
D
i
n
i
c
Dinic
Dinic 使用
b
f
s
bfs
bfs 分层优化:
- b f s bfs bfs 分层,使每次增广只能从当前层流向下一层,避免 d f s dfs dfs 寻找增广路使乱跑增加复杂度(正确性:只要能流向汇点必然存在增广路,必然能分层;最后止于没有增广路)
- d f s dfs dfs 寻找增广路。反向边增加反悔机会,相当于流量退回去。同时使用当前弧优化
当前弧优化:对于一个节点 x x x,当它在 d f s dfs dfs 中走到了第 i i i 条弧时,前 i − 1 i-1 i−1 条弧到汇点的流一定已经被流满而没有可行的路线了,那么当下一次再访问 x x x 节点时,前 i − 1 i−1 i−1 条弧就没有任何意义了,所以我们可以在每次枚举节点 x x x 所连的弧时,改变枚举的起点,这样就可以删除起点以前的所有弧,来达到优化剪枝的效果
代码
#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int N=209,M=5009;
int n,m,s,t,cnt=1; //cnt注意赋为1
LL ans;
int ver[M<<1],nxt[M<<1],head[N];
int d[N],cur[N];
LL edge[M<<1];
queue<int>q;
void Add(int x,int y,int w)
{
ver[++cnt]=y; edge[cnt]=w;
nxt[cnt]=head[x]; head[x]=cnt;
}
bool bfs()
{
memset(d,0,sizeof(d));
while(q.size()) q.pop();
q.push(s); d[s]=1;
while(q.size())
{
int x=q.front(); q.pop();
for(int i=head[x];i;i=nxt[i])
{
if(d[ver[i]]||!edge[i]) continue;
d[ver[i]]=d[x]+1;
q.push(ver[i]);
if(ver[i]==t) return 1;
}
}
return 0;
}
LL dfs(int x,LL flow)
{
if(x==t) return flow;
LL rest=flow;
for(int &i=cur[x];i&&rest;i=nxt[i]) //&为当前弧优化
{
if(!edge[i]||d[ver[i]]!=d[x]+1) continue;
LL k=dfs(ver[i],min(rest,edge[i]));
if(!k) d[ver[i]]=0;
rest-=k; edge[i]-=k; edge[i^1]+=k;
}
return flow-rest;
}
void Dinic()
{
while(bfs())
{
memcpy(cur,head,sizeof(head));
ans+=dfs(s,1ll<<59);
}
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin>>n>>m>>s>>t;
for(int i=1;i<=m;i++)
{
int x,y,w;
cin>>x>>y>>w;
Add(x,y,w); Add(y,x,0);
}
Dinic();
cout<<ans<<'\n';
return 0;
}