Minimum cost maximum flow (MFMC adjacency table without forward edge)

Source: Internet
Author: User

[Sleepy] Pit point: No direction side, each side can only walk once, but is going to walk once the reverse can also walk once, so each input to build four sides.

#include <iostream>#include<algorithm>#include<cstring>#include<cstdio>#include<queue>using namespacestd;intn,m,cnt;inthead[50500],vis[50500],pre[50500];Long Longdis[50500];structedge{intU,v,w,cap,next;} e[50050<<2];voidInitial () {memset (head,-1,sizeof(head));}BOOLSPFA () {memset (PRE,-1,sizeof(pre));  for(intI=0; i<=n+2; i++) {Dis[i]=1e11; } memset (Vis,0,sizeof(VIS)); Queue<int>que; vis[0]=1; Que.push (0); dis[0]=0;  while(!Que.empty ()) {        intD=Que.front ();        Que.pop (); VIS[D]=0;  for(inti=head[d];i!=-1; i=E[i].next) {            intv=e[i].v; if(DIS[V]&GT;DIS[D]+E[I].W &&E[i].cap) {Dis[v]=dis[d]+E[I].W; PRE[V]=i; if(!Vis[v]) {Vis[v]=1;                Que.push (v); }            }        }    }    if(dis[n+1]<1e11) {        return true; }    return false;}intMCMF () {intflow=0, mincost=0;  while(SPFA ()) {Long Longminflow=1e11; intd=n+1;  for(inti=pre[d];i!=-1; i=PRE[E[I].U]) {Minflow=min (Minflow, (Long Long) e[i].cap); } Flow+=Minflow;  for(inti=pre[d];i!=-1; i=PRE[E[I].U]) {E[i].cap-=Minflow; E[i^1].cap+=Minflow; } mincost+=Dis[d]; }    returnMincost;}voidAddintUintVintCapintW) {e[cnt].u=u; E[CNT].V=v; E[CNT].W=W; E[cnt].cap=cap; E[cnt].next=HEAD[E[CNT].U]; Head[u]=cnt++; E[CNT].V=u; E[CNT].U=v; E[CNT].W=-1*W; E[cnt].cap=0; E[cnt].next=HEAD[E[CNT].U]; HEAD[V]=cnt++;}intMain () { while(~SCANF ("%d%d",&n,&m)) {CNT=0;        Initial ();  for(intI=0; i<m;i++){            intu,v,w; scanf ("%d%d%d",&u,&v,&W); Add (U,v,1, W); Add (V,u,1, W); } Add (0,1,2,0); Add (N,n+1,2,0); intans=MCMF (); printf ("%d\n", ans); }    return 0;}

Minimum cost maximum flow (MFMC adjacency table without forward edge)

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.