# 某岛

… : "…アッカリ～ン . .. . " .. .
July 17, 2015

## SPOJ FASTFLOW. Fast Maximum Flow


const int N = 5009, M = 2 * 30009;

//struct Network_Flow{

int D[N], hd[N], suc[M], to[M], cap[M];
int n, m, s, t;

inline void ae(int x, int y, int c){
suc[m] = hd[x], hd[x] = m, to[m] = y, cap[m++] = c,
suc[m] = hd[y], hd[y] = m, to[m] = x, cap[m++] = 0;
}

inline void aee(int x, int y, int c){
suc[m] = hd[x], hd[x] = m, to[m] = y, cap[m++] = c,
suc[m] = hd[y], hd[y] = m, to[m] = x, cap[m++] = c;
}

#define v to[i]
#define c cap[i]
#define f cap[i^1]

LL sap(){
LL z=0; static int cnt[N],cur[N],pre[N];
fill(D,D+n,n),fill(cnt,cnt+n,0);cnt[n]=n;
int u=s;cur[s]=hd[s];while (D[s]){
#define i cur[u]
if (u==t){
int d=INF;for(u=s;u!=t;u=v)checkMin(d,c);
z+=d;for(u=s;u!=t;u=v)f+=d,c-=d;u=s;
}
#undef i
int i;for(i=cur[u];i;i=suc[i]){
if(D[u]+1==D[v]&&c){cur[u]=i,cur[v]=hd[v],pre[v]=u,u=v;break;}
}
if (!i){
if (!--cnt[D[u]])break;
D[u]=1;REP_G(i,u)if(c)checkMax(D[u],D[v]);--D[u];
++cnt[D[u]];if(u==s)cur[u]=hd[u];else u=pre[u];
}
}

return z;
}
#undef f
#undef c
#undef v
//} G;

void init(){
RD(n), m = 2; s = 1, t = n++;
fill(hd, hd+n, 0);

Rush{
int x, y; RD(x, y);
aee(x, y, RD());
}
}

int main(){

#ifndef ONLINE_JUDGE
freopen("/users/xiaodao/desktop/Exercise/in.txt", "r", stdin);
//freopen("/users/xiaodao/desktop/Exercise/out.txt", "w", stdout);

#endif

init(); OT(sap());
}


const int N = 5009, M = 2 * 30009;

//struct Network_Flow{

int D[N], hd[N], suc[M], to[M], cap[M];
int n, m, s, t;

inline void ae(int x, int y, int c){
suc[m] = hd[x], hd[x] = m, to[m] = y, cap[m++] = c,
suc[m] = hd[y], hd[y] = m, to[m] = x, cap[m++] = 0;
}

inline void aee(int x, int y, int c){
suc[m] = hd[x], hd[x] = m, to[m] = y, cap[m++] = c,
suc[m] = hd[y], hd[y] = m, to[m] = x, cap[m++] = c;
}

#define v to[i]
#define c cap[i]
#define f cap[i^1]

bool bfs(){
static int Q[N]; int cz = 0, op = 1;
fill(D, D+n, 0), D[Q[0] = s] = 1; while (cz < op){
int u = Q[cz++]; REP_G(i, u) if (!D[v]&&c){
D[Q[op++]=v] = D[u]+1;
if (v==t) return 1;
}
}
return 0;
}

LL Dinitz(){
LL z=0; while (bfs()){
static int cur[N], pre[N];
int u=s;pre[s]=-1;cur[s]=hd[s];while (~u){
#define i cur[u]
if (u==t){
int d=INF;for(u=s;u!=t;u=v)checkMin(d,c);
z+=d;for(u=s;u!=t;u=v)f+=d,c-=d;u=s;
}
#undef i
int i;for(i=cur[u];i;i=suc[i])if(D[u]+1==D[v]&&c){cur[u]=i,cur[v]=hd[v],pre[v]=u,u=v;break;}
if (!i)D[u]=0,u=pre[u];
}
}
return z;
}
#undef f
#undef c
#undef v
//} G;

void init(){
RD(n), m = 2; s = 1, t = n++;
fill(hd, hd+n, 0);

Rush{
int x, y; RD(x, y);
aee(x, y, RD());
}
}

int main(){

#ifndef ONLINE_JUDGE
freopen("/users/xiaodao/desktop/Exercise/in.txt", "r", stdin);
//freopen("/users/xiaodao/desktop/Exercise/out.txt", "w", stdout);

#endif

init(); OT(Dinitz());
}