codeforces B. Balancer

Description

Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?

Input

The first line contains integer n (1 ≤ n ≤ 50000). The second line contains n non-negative numbers that do not exceed 109, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.

Output

Print the total minimum number of moves.

Sample Input

Input
6
1 6 2 5 3 7
Output
12


题意:一步步的移火柴(只能在相邻火柴间移动)使火柴盒里的火柴数相等所需要的最短步数。

思路:第一个不够的都从第二个拿,第二个不够的都从第三个拿,出现负数没关系。

<span style="font-size:14px;">#include <iostream>
#include <math.h>
#include <stdio.h>
#include <cstdlib>
using namespace std;
long long a[50001];
int main()
{
    int n;
    long long ans;
    long long sum;
    while (cin>>n)
    {
        ans=0;
        sum=0;
        for (int i=0; i<n; i++)
        {
            cin>>a[i];
            sum+=a[i];
        }
        sum/=n;
        for (int i=0; i<n; i++)
        {
            if(a[i]<=sum)
            {
                ans+=sum-a[i];
                a[i+1]-=(sum-a[i]);
            }
            else
            {
                ans+=a[i]-sum;
                a[i+1]+=(a[i]-sum);
            }
            
        }
        cout<<ans<<endl;
    }
    return 0;
}</span>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值