/* ID: shenxyy1 PROG: ditch LANG: C++ */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<iostream> #include<algorithm> #define For(i,j,k) for (i=j;i<=k;i++) #define max(x,y) ((x)>(y)?(x):(y)) #define min(x,y) ((x)<(y)?(x):(y)) using namespace std; const int dmax=1010,INF=1000000000; int a[dmax][dmax],d[dmax],q[dmax],gap[dmax],fa[dmax],low[dmax],m,n,ans; bool p[dmax]; void bfs(){ int f=0,l=1,i,k; memset(d,-1,sizeof(d)); q[1]=n; d[n]=0; gap[0]++; while (f<l){ k=q[++f]; For(i,1,n) if (d[i]!=-1 && a[i][k]){ d[i]=d[k]+1; gap[d[i]]++; q[++l]=k; } } } void sap(){ int i,j,k,t,flag,min; bfs(); t=1; memset(fa,-1,sizeof(fa)); while (d[1]<n){ flag=0; low[1]=INF; For(i,1,n) if (d[t]==d[i]+1 && a[t][i]){ flag=1; break; } if (flag){ low[i]=a[t][i]; low[i]=min(low[t],low[i]); fa[i]=t; t=i; if (t==n){ min=low[n]; ans+=min; j=n; while (j!=1){ a[fa[j]][j]-=min; a[j][fa[j]]+=min; j=fa[j]; } t=1; } }else{ min=n; For(i,1,n) if (a[t][i]) min=min(d[i],min); gap[d[t]]--; if (gap[d[t]]==0) break; d[t]=min+1; gap[d[t]]++; if (t!=1) t=fa[t]; } } } int main(){ int i,j,k,x,y,z; freopen("ditch.in","r",stdin); freopen("ditch.out","w",stdout); scanf("%d%d",&m,&n); For(i,1,m){ scanf("%d%d%d",&x,&y,&z); a[x][y]+=z; } sap(); printf("%d\n",ans); return 0; }