题意:m个点,n条有向边,求从源点1到汇点m的最大流量;
用了Dinic算法写了一遍,回溯的过程是关键,刚开始掌握不好怎么回溯更新,看了网上大神的题解才豁然开朗;
#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#define INF 0x7fffffff
using namespace std;
int e[220][220],m,n,layer[220];
bool bfs()
{
queue<int> q;
memset(layer,0,sizeof(layer));
q.push(1);
layer[1]=1;
while(!q.empty())
{
int t=q.front();
q.pop();
for(int i=1;i<=m;i++)
if(!layer[i]&&e[t][i]>0)
layer[i]=layer[t]+1,q.push(i);
}
return layer[m]==0;
}
int dfs(int s,int u)
{
if(s==m) return u;
int tmp=u;
for(int i=1;i<=m&&tmp;i++)
{
if(layer[s]+1==layer[i]&&e[s][i]>0)
{
int t=dfs(i,min(e[s][i],tmp));
e[s][i]-=t;
e[i][s]+=t;
tmp-=t;
}
}
return u-tmp;
}
int dinic()
{
int ans=0,t=0;
while(!bfs())
while(t=dfs(1,INF))
ans+=t;
return ans;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(e,0,sizeof(e));
for(int i=1;i<=n;i++)
{
int a,b,val;
cin>>a>>b>>val;
e[a][b]+=val;
}
cout<<dinic()<<endl;
}
}