ACM (You are given a sequence a 1 , a 2 ,…, a n a1,a2,…,an consisting of n n integers.)

You are given a sequence
a
1
,
a
2
,…,
a
n
a1,a2,…,an
consisting of
n
n
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
k
k
times.
Input
The first line contains two integers
n
n
and
k
k
(2≤n≤
10
5
,1≤k≤
10
14
)
(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
a
1
,
a
2
,…,
a
n
a1,a2,…,an
(1≤
a
i

10
9
)
(1≤ai≤109)
.
Output
Print 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
k
k
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
题解 :求最小与最大的极差 每次操作只能通过+1或-1 经过k次操作是的极差最小
先 两边同时+1和-1计算在k次变换范围内的极值 如果不够改变 在判断能否改变一次,是极差最小

在这里插入代码#include<stdio.h>
#include
#include
#include
using namespace std;
const int N=1e5+10;
#define ll long long
ll a[N];
ll n,k,x,ans;
int main()
{
   scanf("%lld%lld",&n,&k);
   for(int i=1;i<=n;i++)
    scanf("%lld",&a[i]);
   sort(a+1,a+n+1);
   for(int i=1;i<=n/2;i++)
   {
       int j=n-i+1;
       x=(a[i+1]-a[i]+a[j]-a[j-1])*i;
       if(x<=k)
        k-=x;
       else
       {
           ans=a[j]-a[i]-k/i;
           break;
       }
   }
   printf("%lld",ans);
   return 0;
}

你可能感兴趣的:(ACM (You are given a sequence a 1 , a 2 ,…, a n a1,a2,…,an consisting of n n integers.))