[费用流]2194. 负载平衡问题

题目:acwing2194. 负载平衡问题

分析:

建图方式:

  • 每个点向左右两边建边,容量无穷,花费为1
  • s向高于平均值的建边,容量为差值,花费为0
  • 低于平均值的向t建边,容量为差值,花费为0

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//三年竞赛一场空,不开long long见祖宗
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define x first
#define y second
typedef pair<int, int> pii;
const double eps = 1e-8;
const ll mod = 1e9 + 7;
const int maxn = 200, maxm = 1e6;
const int inf = 0x3f3f3f3f;
struct edge
{
    int ep, val, cost, nex;
}e[maxm];

int head[maxn], tot;

void init()
{
    mem(head, -1), tot = 0;
}

void add(int x, int y, int val, int cost)
{
    e[tot] = {y, val, cost, head[x]}, head[x] = tot++;
    e[tot] = {x, 0, -cost, head[y]}, head[y] = tot++;
}

int n, s, t;
int a[maxn];
int pre[maxn], incf[maxn], dis[maxn];
int inq[maxn];

bool spfa()
{
    queue<int> q; q.push(s); inq[s] = 1;
    mem(dis, inf), dis[s] = 0;
    mem(incf, 0), incf[s] = inf;
    while(!q.empty())
    {
        int now = q.front(); q.pop();
        inq[now] = 0;
        for(int i = head[now]; ~i; i = e[i].nex)
        {
            int ep = e[i].ep;
            if(e[i].val && dis[ep] > dis[now] + e[i].cost)
            {
                dis[ep] = dis[now] + e[i].cost;
                incf[ep] = min(incf[now], e[i].val);
                pre[ep] = i;
                if(inq[ep] == 0)
                    inq[ep] = 1, q.push(ep);
            }
        }
    }
    return incf[t] > 0;
}



int ek()
{
    int cost = 0;
    while(spfa())
    {
        int add = incf[t];
        cost += add * dis[t];
        for(int i = t; i != s; i = e[pre[i] ^ 1].ep)
        {
            e[pre[i]].val -= add, e[pre[i] ^ 1].val += add;
        }
    }
    return cost;
}



int main()
{
    init();
    cin >> n;
    s = 0, t = n + 1;
    int avg = 0;
    for(int i = 1; i <= n; i++) cin >> a[i], avg += a[i];
    avg /= n;
    for(int i = 1; i <= n; i++)
    {
        add(i, i == n ? 1 : i + 1, inf, 1);
        add(i, i == 1 ? n : i - 1, inf, 1);
        if(a[i] > avg) add(s, i, a[i] - avg, 0);
        else if(a[i] < avg) add(i, t, avg - a[i], 0);
    }
    cout << ek() << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值