P3381 【模板】最小费用最大流(spfa板子)

#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long LL;

const int maxm = 5e5+5;
const int INF = 0x3f3f3f3f;

struct edge{
    int u, v, cap, flow, cost, nex;
} edges[maxm];

int head[maxm], cur[maxm], cnt, fa[maxm], d[maxm], n;
bool inq[maxm];

void init() {
    memset(head, -1, sizeof(head));
}

void add(int u, int v, int cap, int cost) {
    edges[cnt] = edge{u, v, cap, 0, cost, head[u]};
    head[u] = cnt++;
}

void addedge(int u, int v, int cap, int cost) {
    add(u, v, cap, cost), add(v, u, 0, -cost);
}

bool spfa(int s, int t, int &flow, LL &cost) {
    for(int i = 0; i <= n+1; ++i) d[i] = INF; //init()
    memset(inq, false, sizeof(inq));
    d[s] = 0, inq[s] = true;
    fa[s] = -1, cur[s] = INF;
    queue<int> q;
    q.push(s);
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        inq[u] = false;
        for(int i = head[u]; i != -1; i = edges[i].nex) {
            edge& now = edges[i];
            int v = now.v;
            if(now.cap > now.flow && d[v] > d[u] + now.cost) {
                d[v] = d[u] + now.cost;
                fa[v] = i;
                cur[v] = min(cur[u], now.cap - now.flow);
                if(!inq[v]) {q.push(v); inq[v] = true;}
            }
        }
    }
    if(d[t] == INF) return false;
    flow += cur[t];
    cost += 1LL*d[t]*cur[t];
    for(int u = t; u != s; u = edges[fa[u]].u) {
        edges[fa[u]].flow += cur[t];
        edges[fa[u]^1].flow -= cur[t];
    }
    return true;
}

int MincostMaxflow(int s, int t, LL &cost) {
    cost = 0;
    int flow = 0;
    while(spfa(s, t, flow, cost));
    return flow;
}

void run_case() {
    init();
    int m, s, t, u, v, w, f;
    cin >> n >> m >> s >> t;
    for(int i = 0; i < m; ++i) {
        cin >> u >> v >> w >> f;
        addedge(u, v, w, f);
    }
    LL cost = 0;
    int flow = MincostMaxflow(s, t, cost);
    cout << flow << " " << cost;
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    run_case();
    cout.flush();
    return 0;
}

 

posted @ 2020-02-06 21:09  GRedComeT  阅读(113)  评论(0编辑  收藏  举报