最小费用最大流MCMF zkw费用流

稀疏图慢死了。。。但是稠密图效果还是很好的

 1 struct MCMF{
 2     struct tedge{int x,y,cap,w,next;}adj[maxm];int ms,fch[maxn];
 3     int vis[maxn],d[maxn],ans,cost,S,T,n;
 4     void init(int n){
 5         this->n=n;ms=0;ans=cost=0;
 6         memset(fch,-1,sizeof(fch));
 7         return;
 8     }
 9     inline void addedge(int u,int v,int cap,int w){
10         adj[ms]=(tedge){u,v,cap,w,fch[u]};fch[u]=ms++;
11         adj[ms]=(tedge){v,u,0,-w,fch[v]};fch[v]=ms++;
12         return;
13     }
14     inline int aug(int u,int f){
15         if(u==T){ans+=cost*f;return f;}
16         int tmp=f;vis[u]=1;
17         for(int i=fch[u];i!=-1;i=adj[i].next){
18             int v=adj[i].y;
19             if(adj[i].cap&&!adj[i].w&&!vis[v]){
20                 int a=aug(v,tmp<adj[i].cap?tmp:adj[i].cap);
21                 adj[i].cap-=a;
22                 adj[i^1].cap+=a;
23                 tmp-=a;
24                 if(!tmp) return f;
25             }
26         } return f-tmp;
27     }
28     inline bool spfa(){
29         for(int i=1;i<=n;i++) d[i]=inf;
30         deque<int>Q;Q.push_back(T);d[T]=0;
31         while(!Q.empty()){
32             int u=Q.front(),tmp;Q.pop_front();
33             for(int i=fch[u];i!=-1;i=adj[i].next)
34                 if(adj[i^1].cap&&(tmp=d[u]-adj[i].w)<d[adj[i].y])
35                     (d[adj[i].y]=tmp)<=d[Q.empty()?S:Q.front()]?Q.push_front(adj[i].y):Q.push_back(adj[i].y);
36         }
37         for(int u=1;u<=n;u++)
38             for(int i=fch[u];i!=-1;i=adj[i].next)
39                 adj[i].w+=d[adj[i].y]-d[u];
40         cost+=d[S];return d[S]<inf;
41     }
42     int costflow(int S,int T){
43         this->S=S;this->T=T;
44         while(spfa())do memset(vis,false,sizeof(vis));while(aug(S,inf));
45         return ans;
46     }
47 }sol;
原文地址:https://www.cnblogs.com/chxer/p/4534304.html