zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Linux 系统使用WordPress开启“固定链接设置”之后部分页面打不开(404)的解决办法
    WordPress安全配置
    去掉Windows2003的自动锁定
    用IP访问wordpress的css和js为何不能加载
    元素伸缩
    Cookie之获设删
    输入0开头的数字,自动纠正
    PHP入门(一)
    node.js(一)
    vue-demo-tab切换
  • 原文地址:https://www.cnblogs.com/GRedComeT/p/12270890.html
Copyright © 2011-2022 走看看