Acwing 2194. 负载平衡问题 (最大流 费用流)

思路

对于每两个相邻仓库 都建立一条容量为无穷大 费用为1的边
对于每个仓库
如果有仓库货物数量小于平均值的 则将其连向汇点 边的容量为与平均值的差
如果有大于平均值的 又源点连一条边容量也为与平均值的差
从而可以达到把所有多余货物从所有多于平均值的仓库流到所有低于平均值的仓库且是由图的内部各仓库之间的流动来完成的

代码

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

using namespace std;

const int N = 110, M = 1010, INF = 1e8;

int n, S, T;
int h[N], e[M], ne[M], f[M], w[M], idx;
int d[N], pre[N], incf[N];
bool st[N];
int s[N];

queue<int> q;

void add(int a, int b, int c, int d)
{
    e[idx] = b, ne[idx] = h[a], f[idx] = c, w[idx] = d, h[a] = idx ++ ;
    e[idx] = a, ne[idx] = h[b], f[idx] = 0, w[idx] = -d, h[b] = idx ++ ;
}

bool spfa()
{
    memset(d, 0x3f, sizeof d);
    memset(incf, 0, sizeof incf);
    q.push(S), incf[S] = INF, d[S] = 0;
    while (q.size())
    {
        int t = q.front();
        q.pop();
        st[t] = false;
        for (int i = h[t]; ~i; i = ne[i])
        {
            int ver = e[i];
            if (f[i] && d[ver] > d[t] + w[i])
            {
                d[ver] = d[t] + w[i];
                pre[ver] = i;
                incf[ver] = min(f[i], incf[t]);
                if (!st[ver])
                {
                    q.push(ver);
                    st[ver] = true;
                }
            }
        }
    }
    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", &n);
    S = 0, T = n + 1;
    
    memset(h, -1, sizeof h);
    
    int tot = 0;
    for (int i = 1; i <= n; i ++ )
    {
        scanf("%d", &s[i]);
        tot += s[i];
        add(i, i < n ? i + 1 : 1, INF, 1);
        add(i, i > 1 ? i - 1 : n, INF, 1);
    }
    
    tot /= n;
    
    for (int i = 1; i <= n; i ++ )
    {
        if (tot > s[i]) add(i, T, tot - s[i], 0);
        else if (tot < s[i]) add(S, i, s[i] - tot, 0);
    }
    
    printf("%d\n", EK());
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值