萌新求助90分,优先队列

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

William_qwq @ 2021-12-15 21:40:29

#include<bits/stdc++.h>
using namespace std;
struct noid
{
    int x,id;
};
struct cmpmax
{
    bool operator ()(noid x,noid y)
    {
        return x.x<y.x;
    }
};
struct cmpmin
{
    bool operator ()(noid x,noid y)
    {
        return x.x>y.x;
    }
};
priority_queue<noid,vector<noid>,cmpmax> qmax;
priority_queue<noid,vector<noid>,cmpmin> qmin;
vector<int> vmax,vmin;
int a[1000010],ex[1000010];
int main()
{
    int n,k,i,j;
    cin>>n>>k;
    for(i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    for(i=1;i<=k;i++)
    {
        qmax.push(noid{a[i],i});
        qmin.push(noid{a[i],i});
    }
    int l=1,r=k;
    while(r<=n)
    {
        while(ex[qmax.top().id]) qmax.pop();
        while(ex[qmin.top().id]) qmin.pop();
        vmax.push_back(qmax.top().x);
        vmin.push_back(qmin.top().x);
        ex[l]=1;
        l++;
        qmax.push(noid{a[r+1],r+1});
        qmin.push(noid{a[r+1],r+1});
        r++;
    }
    for(i=0;i<vmin.size();i++)
    {
        cout<<vmin[i]<<" ";
    }
    cout<<endl;
    for(i=0;i<vmax.size();i++)
    {
        cout<<vmax[i]<<" ";
    }
    return 0;
}

by lsj2009 @ 2021-12-15 21:42:35

请选择单调队列


by lsj2009 @ 2021-12-15 21:46:07

因为按 x 来排序,可能会导致对于某个 id ,他的 x 对于前面很弱,但对于后面很强,所以可能会导致他 id, 让他出队,但 x 不让


by lsj2009 @ 2021-12-15 21:49:00

应该不行,特判样例


by William_qwq @ 2021-12-15 21:59:30

哦……谢谢 @lsj2009


|