XiaoHuang's Space
XiaoHuang's Space
XiaoHuang
May the force be with you.
『题解』洛谷P4016 负载平衡问题
Posted: Dec 11, 2019
Last Modified: Dec 13, 2019
This article was last modified days ago. The content of this post may be outdated!

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

Article License: CC BY-NC-ND 4.0
Article Author: XiaoHuang
  1. 1. Portal
  2. 2. Description
  3. 3. Input
  4. 4. Output
  5. 5. Sample Input
  6. 6. Sample Output
  7. 7. Hint
  8. 8. Solution
  9. 9. Code
  10. 10. Attachment
Newer Post
『题解』洛谷P3376 【模板】网络最大流
Older Post
『题解』BZOJ1798 [AHOI2009]维护序列
Buy me a beer?
-->
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×