CodeForces1244E.Minimizing Difference (二分)

E.Minimizing Difference

You are given a sequence a1,a2,…,an consisting of 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 times.

Input

The first line contains two integers n and k (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,…,an (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 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

Note

In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3,3,5,5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it’s useless since you can’t make the answer less than 2.

In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations.

思路:

自己想的贪心模拟wa爆了,难过。

二分差值,然后枚举每一个a[i]作为最大值或者最小值,然后判断能否在k次操作以内完成就行了,注意既要判断作为最大值也要判断作为最小值

code:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define int long long
const int maxm=1e5+5;
const int inf=1e9;
int a[maxm];
int sum[maxm];//前缀和用于计算区间和
int n,k;
bool check(int mid){
    int last=1;
    for(int i=1;i<=n;i++){//枚举每一个作为最大值
        while(last<i&&a[i]-a[last]>mid)last++;
        int lc=(last-1)*(a[i]-mid)-sum[last-1];//左边需要修改多少
        int rc=sum[n]-sum[i]-(n-i)*a[i];//右边需要修改多少
        if(lc+rc<=k)return 1;//如果k次操作可以完成返回1
    }
    last=1;//这里要从1开始否则下面就不能last++了
    for(int i=1;i<=n;i++){//枚举每一个作为最小值
        while(last+1<=n&&a[last+1]-a[i]<=mid)last++;
        int lc=(i-1)*a[i]-sum[i-1];//左边需要修改多少
        int rc=sum[n]-sum[last]-(n-last)*(a[i]+mid);//右边需要修改多少
        if(lc+rc<=k)return 1;//如果k次操作可以完成返回1
    }
    return 0;
}
signed main(){
    cin>>n>>k;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    sort(a+1,a+1+n);//先排序再前缀和
    for(int i=1;i<=n;i++){
        sum[i]=sum[i-1]+a[i];
    }
    int l=0,r=inf;
    int ans=0;
    while(l<=r){
        int mid=(l+r)/2;
        if(check(mid)){
            ans=mid;
            r=mid-1;
        }else{
            l=mid+1;
        }
    }
    cout<<ans<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值