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.
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.
Print a single line containing the difference between richest and poorest peoples wealth.
4 1 1 1 4 2
2
3 1 2 2 2
0
我的思路:可以试一下暴力,但是应该不会过,我是先求出穷人和富人的上下界,即他们金币的总和除以人数,能除尽的话,那么富人的金币下限就是sum/n,穷人的上限就是sum/n,除不尽的话就是富人sum/n+1, 穷人sum/n。然后分别对穷人的区间和富人的区间进行二分,并求出当富人最多有x金币,穷人最少有y金币时需要多少天,如果天数大于给的天数,那么富人就肯定比x金币多,穷人比y金币少,然后一只二分求天数,最后得到结果。
下面是代码:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<climits>
#include<vector>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#define ll long long
using namespace std;
int a[500005], n, k;
int check_min(int x) //检查贫穷的人
{
ll sum = 0;
for(int i = 0; i < n; i++)
{
if(a[i]>x) break;
sum += x-a[i];
}
if(sum > k) return 0;
else return 1;
}
int check_max(int x) // 检查富有的人
{
ll sum = 0;
for(int i = n-1; i>=0; i--)
{
if(a[i] < x) break;
sum += a[i]-x;
}
if(sum>k) return 0;
else return 1;
}
int main()
{
while(~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 al, ar;
if(sum%n==0) // 判断穷人和富人的上下界
al = sum/n, ar = sum/n;
else
al = sum/n, ar = sum/n+1;
int l = a[0], r = al;
int ansl = a[0], ansr = a[0];
while(r>=l)
{
int mid=(r+l)>>1;
if(check_min(mid))
{
ansl = mid;
l = mid+1;
}
else r = mid-1;
}
l = ar, r = a[n-1];
while(r>=l)
{
int mid=(r+l)>>1;
if(check_max(mid))
{
ansr = mid;
r = mid-1;
}
else l = mid+1;
}
printf("%d\n", ansr-ansl);
}
return 0;
}