求调

P1886 滑动窗口 /【模板】单调队列

sdsswyd @ 2024-08-28 09:07:11

第一次写单调队列,WA+RE+TLE+AC

#include<bits/stdc++.h>
using namespace std;
deque<int>q;
int n,w;
int a[100005];
int main(){
    scanf("%d%d",&n,&w);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    int t=1;
    for(int i=1;i<=n;i++){
        while(!q.empty()&&q.back()>=a[i])q.pop_back();
        q.push_back(a[i]);
        if(i-t>=w&&a[t]==q.front()){
            t++;
            q.pop_front();
        }
        if(i-t>=w&&a[t]!=q.front())t++;
        if(i>=w)printf("%d ",q.front());
    }
    q.clear();
    t=1;
    printf("\n");
    for(int i=1;i<=n;i++){
        while(!q.empty()&&q.back()<=a[i])q.pop_back();
        q.push_back(a[i]);
        if(i-t>=w&&a[t]==q.front()){
            t++;
            q.pop_front();
        }
        if(i-t>=w&&a[t]!=q.front())t++;
        if(i>=w)printf("%d ",q.front());
    }
    return 0;
}

by lch1218 @ 2024-10-19 21:34:12

不想多说了

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,k;
int a[1000010],b[1000010],c[1000010];
deque<int> q;
deque<int> dq;
signed main(){
    cin>>n>>k;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    for(int i=1;i<=n;i++){
        while(!q.empty() && a[q.back()]>a[i])   q.pop_back();
        q.push_back(i);
        if(i>k){
            if(i-k+1>q.front()){
                q.pop_front();
            }
        }
        if(i>=k)    b[i]=a[q.front()];
    }
    for(int i=1;i<=n;i++){
        while(!dq.empty() && a[dq.back()]<a[i]) dq.pop_back();
        dq.push_back(i);
        if(i>k){
            if(i-k+1>dq.front()){
                dq.pop_front();
            }
        }
        if(i>=k)    c[i]=a[dq.front()];
    }
    for(int i=k;i<=n;i++)   cout<<b[i]<<' ';
    cout<<endl;
    for(int i=k;i<=n;i++)   cout<<c[i]<<' ';
    return 0;
}

|