90,超时了

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

Ljh421 @ 2024-02-18 10:16:50

#include <bits/stdc++.h>
using namespace std;
const long long N=1000008;
long long n,k,a[N],da[N],xiao[N];
int main(){

    cin>>n>>k;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    for(int i=1;i<=n-k+1;i++){
        long long maxn=a[i],minn=a[i];
        if(a[i+k-1]>=da[i-1]&&i!=1){ //如果新的数>=上次窗口的最大值 
            da[i]=a[i+k-1];
        }else{
            for(int j=i;j<k+i;j++){
                maxn=max(maxn,a[j]);
            }
            da[i]=maxn;
        }
        if(a[i+k-1]<=xiao[i-1]&&i!=1){
            xiao[i]=a[i+k-1];
        }else{
            for(int j=i;j<k+i;j++){
                minn=min(minn,a[j]);
            }
            xiao[i]=minn;
        }
    }
    for(int i=1;i<=n-k+1;i++){
        cout<<xiao[i]<<" ";
    }
    cout<<endl;
    for(int i=1;i<=n-k+1;i++){
        cout<<da[i]<<" ";
    }

    return 0;
}

by WhileTrueRP @ 2024-02-18 10:23:35

请使用“单调队列”完成本题,你直接暴力的时间复杂度是 O(nk) 肯定不对的,正解的时间复杂度是 O(n)


by WhileTrueRP @ 2024-02-18 10:23:45

@Ljh421


by Ljh421 @ 2024-02-18 10:31:32

@WhileTrueRP 好的,谢谢大佬


by Ljh421 @ 2024-02-19 11:44:09

@WhileTrueRP 暴力做出来了


by WhileTrueRP @ 2024-02-19 13:56:32

@Ljh421 好的!


|