这题二分能过吗
查看原帖
这题二分能过吗
404469
LJN1117楼主2025/8/1 18:33

复杂度 nlogn n log n 应该能过吧不知道为什么

#include<bits/stdc++.h>
#define int long long
#define maxn 3000100
#define re register

using namespace std;

int n,k,mid;
int a[maxn];
deque<int> q1,q2;

bool check(){
    while(!q1.empty()) q1.pop_back();
    while(!q2.empty()) q2.pop_back();
    for(re int i=1;i<=n;i++){
        while(q1.size() && q1.back()>a[i]) q1.pop_back();
        q1.push_back(a[i]);
        while(q2.size() && q2.back()<a[i]) q2.pop_back();
        q2.push_back(a[i]);
        if(i-mid>=1 && q1.front()==a[i-mid]) q1.pop_front();
        if(i-mid>=1 && q2.front()==a[i-mid]) q2.pop_front();
        if(i>=mid && q2.front()-q1.front()<=k) return true;
    }
    return false;
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>k>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    int l=1,r=n,ans;
    while(l<=r){
        mid=(l+r)>>1;
        // cout<<l<<" "<<r<<" "<<mid<<"\n";
        if(check()==1) ans=mid,l=mid+1;
        else r=mid-1;
    }
    cout<<ans<<"\n";
    return 0;
}
2025/8/1 18:33
加载中...