运输问题(费用流,网络流24题)

题意

\(m\) 个仓库和 \(n\) 个零售商店。第 \(i\) 个仓库有 \(a_i\) 个单位的货物;第 \(j\) 个零售商店需要 \(b_j\) 个单位的货物。货物供需平衡,即\(\sum_{i = 1}^m a_i = \sum_{j=1}^nb_j\)

从第 \(i\) 个仓库运送每单位货物到第 \(j\) 个零售商店的费用为 \(c_{ij}\)

对于给定的 \(m\) 个仓库和 \(n\) 个零售商店间运送货物的费用,计算最优运输方案和最差运输方案。

思路

费用流模板题,直接根据题意建图即可。

每个仓库向每个商店,连容量是\(\infty\),费用是\(c_{ij}\)的边。

设立虚拟源点\(S\),向每个仓库连容量是\(a_i\),费用是\(0\)的边。

设立虚拟汇点\(T\),每个商店向\(T\)连容量是\(b_j\),费用是\(0\)的边。

分别求最小费用流和最大费用流即可。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 160, M = 10000 + 310, 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]) {
                    st[ver] = true;
                    que.push(ver);
                }
            }
        }
    }
    return incf[T] > 0;
}

int EK()
{
    int cost = 0;
    while(spfa()) {
        int t = incf[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;
        }
    }
    return cost;
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof(h));
    S = 0, T = n + m + 1;
    for(int i = 1; i <= n; i ++) {
        int x;
        scanf("%d", &x);
        add(S, i, x, 0);
    }
    for(int i = 1; i <= m; i ++) {
        int x;
        scanf("%d", &x);
        add(n + i, T, x, 0);
    }
    for(int i = 1; i <= n; i ++) {
        for(int j = 1; j <= m; j ++) {
            int x;
            scanf("%d", &x);
            add(i, n + j, inf, x);
        }
    }
    printf("%d\n", EK());
    for(int i = 0; i < idx; i += 2) {
        w[i] = -w[i], w[i ^ 1] = -w[i ^ 1];
        f[i] += f[i ^ 1], f[i ^ 1] = 0;
    }
    printf("%d\n", -EK());
    return 0;
}
posted @ 2021-02-18 19:30  pbc的成长之路  阅读(166)  评论(0编辑  收藏  举报