#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
#define MIN(a,b) (a)<(b)?(a):(b)
int flow[205][205];
int cap[205][205];
int lev_net[205][205];
int mx[205];
bool fl[205];
int m,n;
int res;
int dfs(int v)
{
if(v==n)return mx[v];
int ret=0;
for(int i=1;i<=n;i++)
{
if(lev_net[v][i])
{
if(mx[v]==0)
{
fl[v]=0;
return ret;
}
mx[i]=MIN(mx[v],cap[v][i]-flow[v][i]);
int tt=dfs(i);
ret+=tt;
mx[v]-=tt;
flow[v][i]+=tt;
flow[i][v]-=tt;
}
}
return ret;
}
bool bfs()
{
memset(lev_net,0,sizeof(lev_net));
queue<int>q;
q.push(1);
int lev[205];
memset(lev,0x1f,sizeof(lev));
lev[1]=0;
while(!q.empty())
{
int v=q.front();
q.pop();
if(fl[v])continue;
fl[v]=1;
for(int i=1;i<=n;i++)
{
if(cap[v][i]>flow[v][i]&&lev[i]>lev[v])
{
lev_net[v][i]=1;
lev[i]=lev[v]+1;
if(!fl[i])q.push(i);
}
}
}
if(lev[n]==0x1f1f1f1f)return 0;
return 1;
}
void dinic()
{
memset(fl,0,sizeof(fl));
while(bfs())
{
memset(mx,0x1f,sizeof(mx));
res+=dfs(1);
memset(fl,0,sizeof(fl));
}
}
int main()
{
while(~scanf("%d%d",&m,&n))
{
res=0;
memset(flow,0,sizeof(flow));
memset(cap,0,sizeof(cap));
for(int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
cap[u][v]+=w;
}
dinic();
printf("%d\n",res);
}
return 0;
}
一组测试数据:
13 10
1 2 50
1 3 20
2 4 50
2 5 10
3 6 50
3 7 50
4 8 50
5 8 10
6 9 10
7 9 50
8 10 10
9 10 100
8 6 5