【CF609C】 Load Balancing

Tutorial

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);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值