模拟

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);
    }
}

在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值