• 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;
    }
  • 相关阅读:
    Android异步操作总结
    datatable1.9 与datatable1.10以数据差异
    ftk学习记录(形成全屏幕套件)
    linux处置服务Iptables
    Linux课程---9、安装RPM包(RPM的全称是什么)
    Linux课程---8、Linux启动流程
    Linux课程---7、shell技巧(获取帮助命令)
    Linux课程---6、别名管理和网络配置(Linux命令如何记)
    Linux课程---5、常用文件命令和目录命令(创建文件命令)
    英语发音规则---L字母
  • 原文地址:https://www.cnblogs.com/GRedComeT/p/12270890.html
Copyright © 2020-2023  润新知