您的位置:首页 > 理论基础 > 计算机网络

网络流模板 最大流maxflow

2016-09-30 08:37 381 查看
#include <cstdio>
const int inf=2147483647;
int n,m,idx=1;
int to[20201],next[20201],flow[20201],head[102],
dep[102],q[102];
void add(int x,int y,int z)
{
to[++idx]=y;
flow[idx]=z;
next[idx]=head[x];
head[x]=idx;
to[++idx]=x;
flow[idx]=0;
next[idx]=head[y];
head[y]=idx;
return ;
}
bool bfs(int s,int t,int L,int R)
{
for(int i=L;i<=R;++i)
dep[i]=-1;
int l=0,r=0;
dep[q[r++]=s]=1;
while(l<r)
{
int x=q[l++];
for(int i=head[x];i;i=next[i])
if(flow[i]&&dep[to[i]]==-1)
dep[q[r++]=to[i]]=dep[x]+1;
}
return dep[t]!=-1;
}
int dinic(int x,int t,int maxflow)
{
if(x==t)
return maxflow;
int last=maxflow;
for(int i=head[x];i;i=next[i])
if(flow[i]&&dep[to[i]]==dep[x]+1)
{
int tof=dinic(to[i],t,flow[i]<last?flow[i]:last);
if(tof)
{
flow[i]-=tof;
flow[i^1]+=tof;
if(!(last-=tof))
return maxflow;
}
}
dep[x]=-1;
return maxflow-last;
}
int Maxflow(int s,int t,int l,int r)
{
int ans=0;
while(bfs(s,t,l,r))
ans+=dinic(s,t,inf);
return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络流