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 hasci coins. Each day, Robin Hood will take exactly1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's1 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 ink 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 afterk days. Note that the choosing at random among richest and poorest doesn't affect the answer.
The first line of the input contains two integersn andk (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, thei-th of them isci (1 ≤ ci ≤ 109) — initial wealth of thei-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
Lets look at how wealth changes through day in the first sample.
- [1, 1, 4, 2]
- [2, 1, 3, 2] or [1, 2, 3, 2]
So the answer is 3 - 1 = 2
In second sample wealth will remain the same for each person.
题意:有一个大盗,喜好劫富济貧,但他已经老了,不能继续干下去了,打算过k天退隐。在这k天,他每天去最富的人那里劫取 1$ 给了最穷的人,富人也可能变成穷人,问过了k天以后最富的人和最穷的人的钱差距多大。
思路:打算先排一遍序,每次从富人那拿一分钱给了穷人,我们可以从左到右和从右到左各扫一遍,求出前i-1(后n -i)个人和第i个人的金钱相同时需要被给予(被劫)多少钱即L[i](或R[i])。 再扫一遍求比k天之内被给予(或被劫)的钱数小且最接近它的L[i](或R[i]),再在前i个(或后n - j 个)相同的情况下给予(或被劫),然后求最后的贫富差值。还有就是 i>j时说明贫富差值为0(总钱数能平分)或贫富差值为1(总钱数不能被平分)。不懂的(或有地方不对)的话可以交流一下。
没考虑总钱数能不能平分一直WA3。看来得补补脑洞了。。。。
代码时间到:
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<set>
using namespace std;
#define INF 1.0e14;
const int maxn = 1e6+100;
typedef long long LL;
LL A[maxn];
LL L[maxn];
LL R[maxn];
int main(){
int n,k;
cin>>n>>k;
int i,j;
LL sum=0;
for(i=1;i<=n;i++)
scanf("%lld",&A[i]),sum+=A[i];
sort(A+1,A+1+n);
memset(L,0,sizeof L);
memset(R,0,sizeof R);
for(i=2;i<=n;i++)
L[i]=L[i-1]+(A[i]-A[i-1])*(i-1);
for(i=n-1;i>0;i--)
R[i]=R[i+1]+(A[i+1]-A[i])*(n-i);
for(i=2;i<=n;i++)
if(L[i]>k) break;
for(j=n-1;j>0;j--)
if(R[j]>k) break;
if(i-j>1){
if(sum%n==0)
puts("0");
else puts("1");
return 0;
}
LL d=k-L[i-1];
LL Min;
if(d==0){
Min=A[i-1];
}
else{
d/=(i-1);
A[i-1]+=d;
Min=A[i-1];
}
LL Max;
d=k-R[j+1];
if(d==0)
Max=A[j+1];
else {
d/=(n-j);
A[j+1]-=d;
Max=max(A[j+1],A[j]);
}
//cout<<Max<<" "<<Min<<endl;
sum=sum%n ? 1:0;
cout<<max(Max-Min,sum)<<endl;
return 0;
}