负载平衡问题

洛谷 P4016 负载平衡问题

洛谷传送门

JDOJ 2506: 负载平衡问题

JDOJ传送门

Description

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

对于给定的 n个环形排列的仓库的库存量,编程计算使 n个仓库的库存数量相同的最少搬运量。

Input

文件的第 1行中有 1个正整数 n(n<=100),表示有 n个仓库。第 2行中有 n个正整数,表示 n个仓库的库存量。

Output

输出最少搬运量

Sample Input

5 17 9 14 16 4

Sample Output

11

题解:

好看、简洁的题面。

丑恶、难想的思路。

代码:

#include<cstdio>
#include<algorithm>
using namespace std;
int n,a[1000001],set[1000001],sum,avr,ans;
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        sum+=a[i];
    }
    avr=sum/n;
    for(int i=1;i<n;i++)
        set[i]=set[i-1]-avr+a[i];
    sort(set,set+n);
    for(int i=0,j=n-1;i<j;i++,j--)
        ans+=set[j]-set[i];
    printf("%d",ans);
    return 0;
}
posted @ 2019-08-13 12:54  Seaway-Fu  阅读(201)  评论(0编辑  收藏  举报