CF231C To Add or Not to Add

先排序,每次更新一个i就以a[i]为最终的答案来看当前区间里的这些数能否通过不大于k次的+1(排过序了就不会有-1了)操作实现区间内所有的值都为a[i],一旦大于k次就把最前面的pop掉(类似滑动窗口)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ifstream in("input.txt");
ofstream out("output.txt");
#define debug(x) cerr<<"# "<<x<<endl
const ll N=5e6+7;
const ll base=137;
const ll mod=2147483647;
const ll INF=0x7f7f7f7f;
ll n,k,a[N];
int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    scanf("%lld %lld",&n,&k);
    for(int i=1;i<=n;++i)
        scanf("%lld",&a[i]);
    sort(a+1,a+1+n);
    ll j=1,ans=0,maxn=0,fin;
    for(ll i=1;i<=n;++i)
    {
        ans+=a[i];
        while((i-j+1)*a[i]-ans>k)ans-=a[j++];
        if(i-j+1>maxn)maxn=i-j+1,fin=a[i];
    }
    printf("%lld %lld\n",maxn,fin);
    return 0;
}