The maximum flow of minimum fees learned here.
Definition: Graph G uses s as the Source Vertex and T as the sink vertex. C (I, j) is the capacity of G, F (I, j) is the capacity of G, w (I, j) is the unit traffic fee and w (I, j) =-W (J, I ). Cost WF = Σ (fij * wij) (I, j) ε E (G ). That is, when the maximum stream F is obtained, the WF is minimized.
Thought: using the Ford-Fulkerson Algorithm, we constantly find augmented paths in the residual network, the augmented path here is the shortest value of the current network's per unit traffic from S to T. You can select spfa or
Bellman-Ford.
Implementation Code:
Const int n = 110; const int M = N * n * 2; int n, m, K; int B [N], sumb; int C [N] [N]; int S, T; struct node {int from, to, cost, flow, next; //} G [m]; int head [N], T; void Init () {Cl (Head,-1); t = 0;} void add (int u, int V, int F, int W) {G [T]. from = u; G [T]. to = V; G [T]. cost = W; G [T]. flow = f; G [T]. next = head [u]; head [u] = T ++; G [T]. from = V; G [T]. to = u; G [T]. cost =-W; G [T]. flow = 0; G [T]. next = head [V ]; Head [v] = T ++;} void build () {Init (); int I, j; S = 0; t = m + n + 1; for (I = 1; I <= N; ++ I) {Add (S, I, 1, 0); // flow, cost;} for (I = 1; I <= m; ++ I) {for (j = 1; j <= N; ++ J) {If (C [I] [J]) add (J, I + N, 1, 0) ;}}for (j = 1; j <= m; ++ J) {Add (J + N, T, B [J]/K, k); If (B [J] % K> 1) {Add (J + N, T, 1, B [J] % K) ;}} int dis [N]; int pre [N]; bool vis [N]; queue <int> q; bool spfa () {// find the maximum fee while (! Q. empty () Q. pop (); CL (VIS, 0); CL (DIS,-1); CL (PRE,-1); q. push (s); DIS [s] = 0; vis [s] = true; Pre [s] =-1; int U, V, W, I; while (! Q. Empty () {u = Q. Front (); q. Pop (); for (I = head [u]; I! =-1; I = G [I]. next) {v = G [I]. to; W = G [I]. cost; If (G [I]. flow & dis [v] <dis [u] + W) {dis [v] = dis [u] + W; Pre [v] = I; If (! Vis [v]) {vis [v] = true; q. Push (v) ;}} vis [u] = false;} return dis [T]! =-1;} int get_flow () {// augmented path int TMP = T; int res = inf; while (pre [TMP]! =-1) {res = min (Res, G [pre [TMP]. flow); TMP = G [pre [TMP]. from;} TMP = T; while (pre [TMP]! =-1) {G [pre [TMP]. flow-= res; G [pre [TMP] ^ 1]. flow + = res; TMP = G [pre [TMP]. from;} return res;} bool solve () {int cost = 0, flow = 0 ;//... while (spfa () {cost + = dis [T]; flow + = get_flow ();} // printf ("% d \ n", cost, flow); // return cost + N-flow> = sumb ;}
Example: poj2516
Question: http://www.cnblogs.com/vongang/archive/2012/04/14/2447566.html