http://codeforces.com/problemset/problem/671/B
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest’s 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.
After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.
Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn’t affect the answer.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood’s retirement.
The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person.
Output
Print a single line containing the difference between richest and poorest peoples wealth.
题目大意:每一次操作使这 n n n个数中的最大值 − 1 -1 −1,最小值 + 1 +1 +1,若果这 n n n个数都相等的话那么经过这次操作序列没有变化。问经过 k k k次操作后这 n n n个数的最大值与最小值的差值。
思路:愚蠢的我居然还想模拟。应该用二分来做,这题思维挺巧妙的,每次操作其实就是为了让所有数更加接近它们的平均值,我们计算出这个平均值 a v g avg avg,在满足 a [ i ] < a v g a[i]<avg a[i]<avg的所有元素中二分寻找 k k k次操作后所能得到的最大值 M A X MAX MAX,在满足 a [ i ] > a v g a[i]>avg a[i]>avg的元素中二分寻找 k k k次操作后所能得到的最小值 M I N MIN MIN,那么答案不就是 M I N − M A X MIN-MAX MIN−MAX嘛。但是有一个细节问题,假设这 n n n个数的和为 t o t tot tot,当 t o t % n = 0 tot\%n=0 tot%n=0时, l 1 = a m i n , r 1 = a v g , l 2 = a v g , r 2 = a m a x l_1=a_{min},r_1=avg,l_2=avg,r_2=a_{max} l1=amin,r1=avg,l2=avg,r2=amax,否则应该令 l 2 = a v g + 1 l_2=avg+1 l2=avg+1,其它保持不变。比如当 n = 2 n=2 n=2时,两个元素分别为 2 、 3 2、3 2、3,它们的平均值不是整数,不管做多少次操作都不可能让这两个元素相等。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int maxn=5e5+5;
int a[maxn];
int n,k;
int main()
{
scanf("%d %d",&n,&k);
ll sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n);
int l=a[0],r=sum/n,mid;
while(l<=r)
{
mid=l+r>>1;
ll tmp=0;
for(int i=0;i<n;i++)
{
if(a[i]<mid)
tmp+=mid-a[i];
else
break;
}
if(tmp>k)
r=mid-1;
else
l=mid+1;
}
int ans1=r;
l=sum/n;
if(sum%n!=0)
++l;
r=a[n-1];
while(l<=r)
{
mid=l+r>>1;
ll tmp=0;
for(int i=n-1;i>=0;i--)
{
if(a[i]>mid)
tmp+=a[i]-mid;
else
break;
}
if(tmp>k)
l=mid+1;
else
r=mid-1;
}
int ans2=l;
printf("%d\n",ans2-ans1);
return 0;
}