90分,超时了,不知道哪错了

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

Biller12 @ 2024-01-29 16:11:13

#include<bits/stdc++.h>
using namespace std;
int n,k;
static const int maxn=1e6+5;
int a[maxn];
deque<int>s;
deque<int>p;
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1; i<=n; i++)
        scanf("%d",&a[i]);
    for(int i=1; i<=n; i++)
    {
        if(i-k>=p.front())p.pop_front();
        while(!p.empty()&&a[i]<a[p.back()])p.pop_back();
        p.push_back(i);
        if(i>=k)cout<<a[p.front()]<<" ";

    }
    printf("\n");
    for(int i=1; i<=n; i++)
    {
        if(i-k>=s.front())s.pop_front();
        while(!s.empty()&&a[i]>=a[s.back()])s.pop_back();
        s.push_back(i);
        if(i>=k)cout<<a[s.front()]<<" ";
    }
    printf("\n");

}

by _zuoqingyuan @ 2024-01-29 16:13:58

用 printf 而不是 cout 应该就可以了吧


by _zuoqingyuan @ 2024-01-29 16:23:34

#include<bits/stdc++.h>
using namespace std;
int n,k;
static const int maxn=1e6+5;
int a[maxn];
deque<int>s;
deque<int>p;
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1; i<=n; i++)
        scanf("%d",&a[i]);
    for(int i=1; i<=n; i++)
    {
        if(!p.empty()&&i-k>=p.front())p.pop_front();
        while(!p.empty()&&a[i]<a[p.back()])p.pop_back();
        p.push_back(i);
        if(i>=k)printf("%d ",a[p.front()]);

    }
    printf("\n");
    for(int i=1; i<=n; i++)
    {
        if(!s.empty()&&i-k>=s.front())s.pop_front();
        while(!s.empty()&&a[i]>=a[s.back()])s.pop_back();
        s.push_back(i);
        if(i>=k)printf("%d ",a[s.front()]);
    }
    printf("\n");

}

by Biller12 @ 2024-01-30 18:10:03

@zuoqingyuan 可算给我解决了(我刚入门),谢谢大佬


|