[存模板]最小费用最大流 MCMF

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#define SF scanf
#define PF printf
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 500;
const int MAXM = 500 * 500 / 2;
struct Node {
    int u, v, c, f, cost;
};
template <int maxn, int maxm>
struct MCMF {
    int n, m, s, t;
    vector <Node> Edge;
    vector <int> G[maxn+10];
    int inq[maxn+10], d[maxn+10], p[maxn+10], a[maxn+10];
    void init(int n) {
        this->n = n;
        for(int i = 0; i < n; i++) G[i].clear();
        Edge.clear();
    }
    void add(int u, int v, int c, int cost) {
        Edge.push_back((Node) { u, v, c, 0, cost } );
        Edge.push_back((Node) { v, u, 0, 0, -cost } );
        m = Edge.size();
        G[u].push_back(m-2); G[v].push_back(m-1);
    }
    bool SPFA(int s, int t, int &Flow, int &Cost)
    {
        memset(d, 0x3f, sizeof(d));
        memset(inq, 0, sizeof(inq));
        d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
        queue <int> q;
        q.push(s);
        while(!q.empty())
        {
            int u = q.front(); q.pop();
            inq[u] = 0;
            for(int i = 0; i < G[u].size(); i++)
            {
                int v = Edge[G[u][i]].v, c = Edge[G[u][i]].c, f = Edge[G[u][i]].f, cost = Edge[G[u][i]].cost;
                if(c > f && d[v] > d[u] + cost) {
                    d[v] = d[u] + cost;
                    p[v] = G[u][i];
                    a[v] = min(a[u], c - f);
                    if(!inq[v]) { q.push(v); inq[v] = true; }
                }
            }
        }
        if(d[t] == INF) return false;
        Flow += a[t];
        Cost += d[t] * a[t];
        int u = t;
        while(u != s) {
            Edge[p[u]].f += a[t];
            Edge[p[u]^1].f -= a[t];
            u = Edge[p[u]].u;
        }
        return true;
    }
    int Mincost(int s, int t) {
        int Flow = 0, Cost = 0;
        while(SPFA(s, t, Flow, Cost)) ;
        return Cost;
    }
};
MCMF <MAXN+10, MAXM+10> sap;
int main()
{
    int n, m;
    SF("%d%d", &n, &m);
    sap.init(n);
    for(int i = 1; i <= m; i++)
    {
        int u, v, c, cost;
        SF("%d%d%d%d", &u, &v, &c, &cost);
        sap.add(u, v, c, cost);
    }
    int ans = sap.Mincost(1, n);
    PF("%d", ans);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值