『题解』洛谷P4016 负载平衡问题


title:
categories:
tags:
-
mathjax: true
---

Problem Portal

Portal1:Luogu

Portal2: LibreOJ

Description

\(G\)公司有\(n\)个沿铁路运输线环形排列的仓库,每个仓库存储的货物数量不等。如何用最少搬运量可以使\(n\)个仓库的库存数量相同。搬运货物时,只能在相邻的仓库之间搬运。

Input

文件的第\(1\)行中有\(1\)个正整数\(n\),表示有\(n\)个仓库。

\(2\)行中有\(n\)个正整数,表示\(n\)个仓库的库存量。

Output

输出最少搬运量。

Sample Input

5
17 9 14 16 4

Sample Output

11

Hint

对于\(100\%\)的测试数据:\(1 \leq n \leq 100\)

Solution

虽然说是网络流24题,其实贪心+排序就够了。

Code

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

using namespace std;

const int MAXN=105;
int n, a[MAXN]; 
int main() {
    scanf("%d",&n);
    int sum=0;
    for (int i=1; i<=n; i++) {
        scanf("%d",&a[i]);
        sum+=a[i];
    }
    sum/=n;
    for (int i=1; i<=n; i++)
        a[i]+=a[i-1]-sum;
    sort(a+1, a+n+1);
    sum=a[(n+1)>>1];//尽量用位运算,比较快
    int ans=0;
    for (int i=1; i<=n; i++)
        ans+=abs(a[i]-sum);//计算每一个距离中间的位置
    printf("%d\n",ans);
    return 0;
}

Attachment

测试数据下载:https://www.lanzous.com/i3juukh

猜你喜欢

转载自www.cnblogs.com/shenxiaohuang/p/11221091.html
今日推荐