Minimum cost flow Template

Source: Internet
Author: User


Compared to the maximum flow template: Maximum flow template (Dinic)

Paste the minimum fee flow template:

const int OO=1E9;CONST int Mm=11111111;const int mn=888888;int node,src,dest,edge;int ver[mm],flow[mm],cost[mm],nex[ Mm];int head[mn],dis[mn],p[mn],q[mn],vis[mn];/** These variables are basically the same as the maximum flow, which increases the cost for the edge, and P records the opposite side of the node on the feasible stream */void prepare (int _    Node,int _src,int _dest) {node=_node,src=_src,dest=_dest;    for (int i=0; i<node; i++) head[i]=-1,vis[i]=0; edge=0;}    void Addedge (int u,int v,int f,int c) {ver[edge]=v,flow[edge]=f,cost[edge]=c,nex[edge]=head[u],head[u]=edge++; ver[edge]=u,flow[edge]=0,cost[edge]=-c,nex[edge]=head[v],head[v]=edge++;}    /** above with the maximum flow *//**SPFA to find the shortest way, and P records the shortest way side */bool SPFA () {int i,u,v,l,r=0,tmp;    for (i=0; i<node; ++i) Dis[i]=oo;    dis[q[r++]=src]=0;    P[src]=p[dest]=-1; for (l=0; l!=r; (++L&GT;=MN) l=0:l) for (i=head[u=q[l]],vis[u]=0; i>=0; i=nex[i]) if (flow[i]&&dis[v=ver[i]]&gt                ;(Tmp=dis[u]+cost[i]) {dis[v]=tmp;                p[v]=i^1;                if (Vis[v]) continue; Vis[q[r++]=v]=1;            if (r>=mn) r=0; } return p[dest]>-1;}    /** the source point to the sink point of a shortest possible flow, and constantly find such a viable flow */int Spfaflow () {int i,ret=0,delta;        while (SPFA ()) {for (i=p[dest],delta=oo; i>=0; i=p[ver[i]) if (Flow[i^1]<delta) delta=flow[i^1];        for (I=p[dest]; i>=0; i=p[ver[i]) Flow[i]+=delta,flow[i^1]-=delta;    Ret+=delta*dis[dest]; } return ret;}


Minimum cost flow Template

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.