Denote s — the sum of elements in array. If s is divisible by n then the balanced array consists of n elements . In this case the difference between maximal and minimal elements is 0. Easy to see that in any other case the answer is greater than 0. On the other hand the array consists of
numbers
and
numbers
is balanced with the difference equals to 1. Let's denote this balanced array b. To get array b let's sort array a in nonincreasing order and match element ai to element bi. Now we should increase some elements and decrease others. In one operation we can increase some element and decrease another, so the answer is
第二个例子,之前一直想的是l=10,r=11,碰到比l小的ans加,碰到比r大的ans减,但是会有问题,因为平衡后值等于r的个数是可以算的。。
#include <stdio.h>
#include <algorithm>
#include <math.h>
using namespace std;
int n,a[111000],b[100100],c[100100];
int main()
{
scanf("%d",&n);
int sum=0;
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
int p=sum/n,l,r;
if(p*n==sum)
l=r=p;
else
{
l=p;
r=p+1;
}
sort(a,a+n);
int k=sum%n;
for(int i=0; i<n; i++)
{
if(i<n-k)
c[i]=l;
else
c[i]=r;
}
int ans=0;
for(int i=0; i<n; i++)
ans+=fabs(a[i]-c[i]);
printf("%d\n",ans/2);
}