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?
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.
Print the total minimum number of moves.
6 1 6 2 5 3 7
12
题意:移动火柴使得每堆数量相同。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
long long num[50010];
int main()
{ int n,i,j;
long long sum,ans,k;
scanf("%d",&n);
sum=0;ans=0;
for(i=1;i<=n;i++)
{ scanf("%I64d",&num[i]);
sum+=num[i];
}
sum=sum/n;
for(i=1;i<=n;i++)
{ if(num[i]==sum)
continue;
else if(num[i]>sum)
{ k=num[i]-sum;
ans+=k;
num[i+1]+=k;
}
else if(num[i]<sum)
{ k=sum-num[i];
ans+=k;
num[i+1]-=k;
}
}
printf("%I64d\n",ans);
}