zoukankan      html  css  js  c++  java
  • 费用流模板

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    
    using namespace std;
    
    const int N = 5010, M = 100010, inf = 1e8;
    
    int n, m, S, T;
    int h[N], e[M], ne[M], f[M], w[M], idx;
    int pre[N], d[N], incf[N];
    bool st[N];
    
    void add(int a, int b, int c, int d)
    {
        e[idx] = b, f[idx] = c, w[idx] = d, ne[idx] = h[a], h[a] = idx ++;
        e[idx] = a, f[idx] = 0, w[idx] = -d, ne[idx] = h[b], h[b] = idx ++;
    }
    
    bool spfa()
    {
        memset(d, 0x3f, sizeof(d));
        memset(incf, 0, sizeof(incf));
        queue<int> que;
        que.push(S);
        d[S] = 0, incf[S] = inf;
        st[S] = true;
        while(que.size()) {
            int t = que.front();
            que.pop();
            st[t] = false;
            for(int i = h[t]; ~i; i = ne[i]) {
                int ver = e[i];
                if(d[ver] > d[t] + w[i] && f[i]) {
                    d[ver] = d[t] + w[i];
                    pre[ver] = i;
                    incf[ver] = min(f[i], incf[t]);
                    if(!st[ver]) {
                        que.push(ver);
                        st[ver] = true;
                    }
                }
            }
        }
        return incf[T] > 0;
    }
    
    void EK(int &flow, int &cost)
    {
        flow = 0, cost = 0;
        while(spfa()) {
            int t = incf[T];
            flow += t, cost += t * d[T];
            for(int i = T; i != S; i = e[pre[i] ^ 1]) {
                f[pre[i]] -= t;
                f[pre[i] ^ 1] += t;
            }
        }
    }
    
    int main()
    {
        scanf("%d%d%d%d", &n, &m, &S, &T);
        memset(h, -1, sizeof(h));
        while(m --) {
            int a, b, c, d;
            scanf("%d%d%d%d", &a, &b, &c, &d);
            add(a, b, c, d);
        }
        int flow, cost;
        EK(flow, cost);
        printf("%d %d
    ", flow, cost);
        return 0;
    }
    
  • 相关阅读:
    连载日记
    自我介绍
    test0710 二分专题
    test0709 搜索专题
    test0705
    test0704
    [题解] [HNOI2015]落忆枫音
    test0606
    test0523
    备份
  • 原文地址:https://www.cnblogs.com/miraclepbc/p/14410670.html
Copyright © 2011-2022 走看看