Const int M = 20010, ME = 500000; const int INF = 0x3f3fffff; // ****************************** int Head [M], next [ME], Num [ME], Flow [ME], Cap [ME], Cost [ME], Q [M], InQ [M], Len [M], pre_edge [M]; class MaxFlow {public: void clear () {memset (Head,-1, sizeof (Head); memset (Flow, 0, sizeof (Flow);} void addedge (int u, int v, int cap, int cost) {Next [top] = Head [u]; Num [top] = v; cap [top] = cap; Cost [top] = cost; Head [u] = top ++; Nex T [top] = Head [v]; Num [top] = u; Cap [top] = 0; Cost [top] =-cost; head [v] = top ++;} int solve (int s, int t) // returns the final cost {int cost = 0; while (SPFA (s, t )) {int cur = t, minflow = INF; while (cur! = S) {if (minflow> Cap [pre_edge [cur]-Flow [pre_edge [cur]) minflow = Cap [pre_edge [cur]-Flow [pre_edge [cur]; cur = Num [pre_edge [cur] ^ 1];} cur = t; while (cur! = S) {Flow [pre_edge [cur] + = minflow; Flow [pre_edge [cur] ^ 1]-= minflow; cost + = minflow * Cost [pre_edge [cur]; cur = Num [pre_edge [cur] ^ 1] ;}} return cost;} private: bool SPFA (int s, int t) {fill (Len, Len + M, INF); Len [s] = 0; int head =-1, tail =-1, cur; Q [++ head] = s; while (head! = Tail) {++ tail; if (tail> = M) tail = 0; cur = Q [tail]; for (int I = Head [cur]; I! =-1; I = Next [I]) {if (Cap [I]> Flow [I] & Len [Num [I]> Len [cur] + Cost [I]) {Len [Num [I] = Len [cur] + Cost [I]; pre_edge [Num [I] = I; if (! InQ [Num [I]) {InQ [Num [I] = true; ++ head; if (head> = M) head = 0; Q [head] = Num [I] ;}} InQ [cur] = false;} return Len [t]! = INF;} int top;} my;