最小费用最大流模板

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#define LL long long
#define inf 0x3f3f3f3f
#define fr first
#define sc second
#define range(i,a,b) for(auto i=a;i<=b;++i)
#define itrange(i,a,b) for(auto i=a;i!=b;++i)
#define rerange(i,a,b) for(auto i=a;i>=b;--i)
#define fill(arr,tmp) memset(arr,tmp,sizeof(arr))
using namespace std;
const int Vmxn=int(1e5+5);
namespace MCMF{
    struct edge{
        int from,to,cap,flow,cost;
        edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){}
    };
    int n,m;
    vector<edge>edges;
    vector<int>G[Vmxn];
    bool inq[Vmxn];
    int d[Vmxn],p[Vmxn],a[Vmxn];
    void init(int sz){
        n=sz;
        range(i,0,n)G[i].clear();
        edges.clear();
    }
    void add_edge(int from,int to,int cap,int cost){
        edges.emplace_back((edge(from,to,cap,0,cost));
        edges.emplace_back(edge(to,from,0,0,-cost));
        m=int(edges.size());
        G[from].push_back(m-2);
        G[to].push_back(m-1);
    }
    bool spfa(int s,int t,int&flow,LL&cost){
        fill(d,inf);fill(inq,0);
        d[s]=0;inq[s]=true;p[s]=0;a[s]=inf;
        queue<int>q;
        q.push(s);
        while(not q.empty()){
            int u=q.front();
            q.pop();
            inq[u]=0;
            range(i,0,G[u].size()-1){
                edge& e=edges[G[u][i]];
                if(e.cap>e.flow and d[e.to]>d[u]+e.cost){
                    d[e.to]=d[u]+e.cost;
                    p[e.to]=G[u][i];
                    a[e.to]=min(a[u],e.cap-e.flow);
                    if(not inq[e.to]){
                        q.push(e.to);
                        inq[e.to]=true;
                    }
                }
            }
            if(d[t]==inf)return false;
            flow+=a[t];
            cost+=1LL*d[t]*a[t];
            for(int u=t;u!=s;u=edges[p[u]].from){
                edges[p[u]].flow+=a[t];
                edges[p[u]^1].flow-=a[t];
            }
            return true;
        }
    }
    int MincostMaxflow(int s,int t,LL&cost){
        int flow=0;
        cost=0;
        while(spfa(s,t,flow,cost));
        return flow;
    }
}
void init(){

}
void solve(){

}
int main() {
    init();
    solve();
    return 0;
}
View Code

 

posted @ 2018-08-01 11:56  RhythmLian  阅读(182)  评论(0编辑  收藏  举报