Explanation: Find the path with the smallest cost between S-T, that is, the shortest path of a single source. If t is no longer accessed, the algorithm ends. Otherwise, find the minimum residual capacity C based on the shortest path, add the maximum traffic plus C, then update the edge of the shortest path, subtract C from the forward arc, and add c to the reverse arc, and create a reverse billing edge. The minimum cost is the cost of each edge. The cost of each edge = unit cost * C.
A more general model is the minimum cost and the maximum flow.
Template:
# Define maxn 20005 struct {int V, W, C, next, RE; // re records the subscript of the inverse edge, C is the cost, W is the traffic} e [maxn]; int n, m, CNT; int head [maxn], que [maxn], pre [maxn], DIS [maxn]; bool vis [maxn]; void addedge (int u, int V, int W, int c) {e [CNT]. V = V, E [CNT]. W = W, E [CNT]. C = C; E [CNT]. next = head [u]; E [CNT]. re = CNT + 1, head [u] = CNT ++; E [CNT]. V = u, E [CNT]. W = 0, E [CNT]. C =-C; E [CNT]. next = head [v]; E [CNT]. re = cnt-1, head [v] = CNT ++;} bool spfa () {int I, L = 0, r = 1; fo R (I = 0; I <= N; I ++) dis [I] = inf, vis [I] = false; DIS [0] = 0, que [0] = 0, vis [0] = true; while (L <r) {int u = que [L ++]; for (I = head [u]; i! =-1; I = E [I]. next) {int v = E [I]. v; If (E [I]. W & dis [v]> dis [u] + E [I]. c) {dis [v] = dis [u] + E [I]. c; Pre [v] = I; If (! Vis [v]) {vis [v] = true; que [R ++] = V ;}} vis [u] = false ;} if (DIS [N] = inf) return false; return true;} int change () {int I, P, sum = inf, ANS = 0; for (I = N; I! = 0; I = E [E [p]. re]. v) {P = pre [I]; sum = min (sum, E [p]. w) ;}for (I = N; I! = 0; I = E [E [p]. re]. v) {P = pre [I]; E [p]. w-= sum; E [E [p]. re]. W + = sum; ans + = sum * E [p]. c; // The unit traffic fee recorded in C must be multiplied by the traffic fee.} Return ans;} int dinic () {int sum = 0; while (spfa () sum + = change (); Return sum ;}
Maximum Flow with minimum cost