codefores 352 D. Robin Hood

D. Robin Hood
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Examples
input
4 1
1 1 4 2
output
2
input
3 1
2 2 2
output
0
Note

Lets look at how wealth changes through day in the first sample.

  1. [1, 1, 4, 2]
  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.

题意:

给你n个数,k天,每一天最富的减一,最穷的加一,求k天后最富的减去最穷的值

思路:

先增加穷人的值,在减少富人的值;

#include<bits/stdc++.h>
using namespace std;
long long  a[500005];
int main()
{
long long  n,k, sum=0;
cin>>n>>k;
for(int i=0;i<n;i++)
scanf("%lld",&a[i]),sum+=a[i];


sort(a,a+n);
long long r=n-1,l=0,m1=k,m2=k,al,ar,c1=1,c2=1;
int k1=k,k2=k;
while(l<n-1)
{
if(c1*(a[l+1]-a[l])<=m1)
{
m1-=c1*(a[l+1]-a[l]);
c1++;
l++;
}
else
break;

}
al=a[l]+m1/c1;
while(r>0)
{
if(c2*(a[r]-a[r-1])<=m2)
{
m2-=c2*(a[r]-a[r-1]);
c2++;
r--;
}
else 
break;
}
ar=a[r]-m2/c2;
if(al>=ar)
{
if(sum%n)
printf("1\n");
else
printf("0\n");
}
else
printf("%lld",ar-al);

 } 


你可能感兴趣的:(codefores 352 D. Robin Hood)