代码:
#include<bits/stdc++.h>
#define N 100005
#define M 100005
#define INF 0x7fffffff
using namespace std;
int n,m,c=0,s,t;
int head[N],deep[N],cur[N];
struct ljh
{
int next,w,to;
}e[2*M];
inline void add(int x,int y,int z)
{
e[c].next=head[x];
e[c].to=y;
e[c].w=z;
head[x]=c++;
}
bool bfs(int s,int t)
{
queue<int>q;
memset(deep,0,sizeof(deep));
deep[s]=1;
q.push(s);
while(!q.empty())
{
int now=q.front();
q.pop();
for(int i=head[now];i!=-1;i=e[i].next)
{
int nex=e[i].to;
if(deep[nex]==0&&e[i].w!=0)
{
deep[nex]=deep[now]+1;
q.push(nex);
}
}
}
return deep[t]!=0;
}
int dfs(int x,int t,int maxflow)
//表示从x出发寻找到汇点t的增广路,寻找到最大流maxflow为止,并相应的增广。返回值为实际增广了多少(因为有可能找不到maxflow流量的增广路)
{
if(x==t)return maxflow;
int ans=0;
for(int i=cur[x];i!=-1;i=e[i].next)
{
int nex=e[i].to;
if(deep[nex]!=deep[x]+1||e[i].w==0||ans>=maxflow)continue;
//已经大于了它的最大的那个流量了,就说明后面流到t的流量已经被限制成maxflow了,如果我已经流了那么多了,还继续流的话是流不下去了的
cur[x]=i;//此路可行,记录此路,其实感觉实际上并没有什么用
int k=dfs(nex,t,min(e[i].w,maxflow-ans));
//实际上这部取min的操作就是比较依次流过选取最小的流量,如果有分流的情况,比如说2分成了1 1,就是说之前的道路限制了只能流过2的流量,之后再走,那么我只能对这个2的流量进行分流
//就算当前道路的流量再大也不行,因为之前来的只有那么大,所以是maxflow-ans
e[i].w-=k;
e[i^1].w+=k;
ans+=k;
}
if(ans==0)deep[x]=-2;//炸点优化
return ans;
}
int Dinic(int s,int t)
{
int ans=0;
while(bfs(s,t))
{
memcpy(cur,head,sizeof(head));//当前弧优化,初始化
ans+=dfs(s,t,INF);
}
return ans;
}
int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,0);//注意这里反向的长度为0
}
scanf("%d%d",&s,&t);
printf("%d\n",Dinic(s,t));
}
/*
6 7
1 2 2
2 5 1
1 3 1
3 4 1
2 4 2
5 6 1
4 6 2
1 6
4 5
1 2 40
1 4 20
2 4 20
2 3 30
3 4 10
1 4
5 6
1 2 4
2 4 3
4 5 5
3 5 4
2 3 2
1 3 6
1 5
*/