You are given a sequence a1,a2,…,ana1,a2,…,an consisting of nn integers.
You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.
Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than kk times.InputThe first line contains two integers nn and kk (2≤n≤105,1≤k≤1014)(2≤n≤105,1≤k≤1014) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.
The second line contains a sequence of integers a1,a2,…,ana1,a2,…,an (1≤ai≤109)(1≤ai≤109).OutputPrint the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than kk times.Examples
Input
4 5
3 1 7 5
Output
2
Input
3 10
100 100 100
Output
0
Input
10 9
4 5 5 7 5 4 5 2 4 3
Output
1
题意:找出最大值与最小值在k次的变化下差的最小值。之前打过一次,今天再看时发现又忘了怎么打了。
#include<string.h>
#include<algorithm>
using namespace std;
bool cmp(long long a,long long b)
{
return a<b;
}
long long m[1001000];
int main()
{
long long n,k;
while(~scanf("%lld %lld",&n,&k))
{
memset(m,0,sizeof(m));
long long i,j,sum,ans=0;
for(i=1;i<=n;i++)
scanf("%lld",&m[i]);
sort(m+1,m+n+1,cmp);
for(i=1;i<=n/2;i++)//分别从两侧同时开始寻找
{
sum=((m[i+1]-m[i])+(m[n-i+1]-m[n-i]))*i;//每次一侧都会有i个数同时变化。
if(sum<=k)
k=k-sum;
else
{
ans=m[n-i+1]-m[i]-k/i;//最后还要判断以一下可不可以再缩小。
break;
}
}
printf("%lld\n",ans);
}
}
在这里插入代码片