Maximum Flow with minimum cost

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.