题目描述
有n个点,m条有向边,对于每条边u->v,可以从u到v流w容量,问,1到n最大可以流多少容量。
输入
第一行输入n,m
接下来m行每行输入u, v, w
输出
输出最大流
样例输入
4 5
1 2 40
1 4 20
2 4 20
2 3 30
3 4 10
样例输出
50
提示
【数据规模和约定】
1<=n<=2000
1<=m<=10000
0<=w<=10000
开始填网络流的坑,此题是最大流EK算法(找增广路)的模版题,网络流中的反向边真是精妙!
EK算法的复杂度为
nm2
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m,x,y,z,ans,tot,src,tar;
int head[2005],Next[20005],to[20005],cap[20005];
int pre[2005],path[2005],vis[2005],g[200005];
void add(int x,int y,int z)
{
Next[tot]=head[x];
to[tot]=y;
cap[tot]=z;
head[x]=tot;
tot++;
}
int bfs()
{
int t=0,w=1;
for(int i=1;i<=n;i++) vis[i]=0;
g[1]=src;
pre[src]=-1;path[src]=-1;vis[src]=1;
while(t<w)
{
t++;
int x=g[t];
for(int i=head[x];i!=-1;i=Next[i])
{
int y=to[i],z=cap[i];
if(vis[y]) continue;
if(z<=0) continue;
pre[y]=x;path[y]=i;vis[y]=1;
if(y==tar) return 1;
w++;
g[w]=y;
}
}
return 0;
}
int ek()
{
int ret=0;
while(bfs())
{
int x=tar,flow=1e9;
while(x!=src)
{
flow=min(flow,cap[path[x]]);
x=pre[x];
}
x=tar;
while(x!=src)
{
cap[path[x]]-=flow;
cap[path[x]^1]+=flow;
x=pre[x];
}
ret+=flow;
}
return ret;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++) head[i]=-1;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,0);
}
src=1;tar=n;
ans=ek();
cout<<ans;
return 0;
}