#include<iostream>
/*
题意:就是寻找从源点到汇点的最大流!
要注意的是每两个点的流量可能有多个,也就是说有重边,所以要把两个点的所有的流量都加起来
就是这两个点之间的流量了! 思路:建图之后直接套用最大流算法(EK, 或者是Dinic算法) 图解Dinic算法流程!
*/
#include<queue>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define INF 0x3f3f3f3f3f3f3f3f
#define N 205
using namespace std;
typedef long long LL;
LL cap[N][N]; int m, n;
LL maxFlow;
int d[N];
queue<int>q; bool bfs(){
q.push();
memset(d, , sizeof(d));
d[]=;
while(!q.empty()){
int u=q.front();
q.pop();
for(int v=; v<=n; ++v)
if(!d[v] && cap[u][v]>){
d[v]=d[u]+;
q.push(v);
}
}
if(!d[n]) return false;
return true;
} LL dfs(int u, LL flow){
if(u==n) return flow;
for(int v=; v<=n; ++v)
if(d[v]==d[u]+ && cap[u][v]>){
LL a=dfs(v, min(flow, cap[u][v]));
if(a==) continue;//如果a==0 说明没有找到从起点到汇点的增广路, 然后换其他路接着寻找!
cap[u][v]-=a;
cap[v][u]+=a;
return a;
}
return ;
} void Dinic(){
LL flow;
while(bfs()){//利用bfs构造好层次图,这样dfs在寻找阻塞流的时候,就不会盲目的寻找了!
while(flow=dfs(, INF)) maxFlow+=flow;//利用构造好的层次图不断的寻找阻塞流!
}
} int main(){
while(scanf("%d%d", &m, &n)!=EOF){
memset(cap, , sizeof(cap));
while(m--){
int u, v;
LL w;
scanf("%d%d%lld", &u, &v, &w);
cap[u][v]+=w;
}
maxFlow=;
Dinic();
printf("%lld\n", maxFlow);
}
return ;
}
//EK算法同样搞定
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
typedef __int64 LL;
LL cap[][];
int pre[];
LL a[];
int m, n;
queue<int>q;
LL maxFlow;
bool spfa(){
while(!q.empty()) q.pop();
memset(a, , sizeof(a));
q.push();
a[]=INF;
while(!q.empty()){
int u=q.front();
q.pop();
for(int v=; v<=n; ++v)
if(!a[v] && cap[u][v]>){
pre[v]=u;
a[v]=min(a[u], cap[u][v]);
q.push(v);
}
if(a[n]) break;
}
if(!a[n]) return false;
return true;
} void EK(){
maxFlow=;
while(spfa()){
int u=n;
maxFlow+=a[n];
while(u!=){
cap[pre[u]][u]-=a[n];
cap[u][pre[u]]+=a[n];
u=pre[u];
}
}
}
int main(){
while(scanf("%d%d", &m, &n)!=EOF){
memset(cap, , sizeof(cap));
while(m--){
int u, v;
LL w;
scanf("%d%d%I64d", &u, &v, &w);
cap[u][v]+=w;
}
EK();
printf("%I64d\n", maxFlow);
}
return ;
}