队列

模拟队列

清晰明了。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;


int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    int m;
    cin >> m;
    vector<int> Q(m+10,0);
    int head=0, tail=0;
    int v;
    string opt;
    while (m -- ){
        cin >> opt;
        if(opt=="push"){cin>>v;Q[tail++]=v;}
        else if(opt=="pop")head++;
        else if(opt=="empty")cout << (head==tail?"YES":"NO")<<endl;//三目运算符输出的时候要加括号
        else if(opt=="query")cout<<Q[head]<<endl;
    }
    
    return 0;
}

单调队列

#include <iostream>
#include <cstring>
#include <algorithm>
#include <deque>
#include <vector>


using namespace std;

struct Node{
    int num,pos;
};
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    int n,k;
    cin >> n >> k;
    deque<Node> D(k+10);
    vector<int> N(n);
    
    for (int i = 0; i < n; i ++ ) cin>>N[i];


    D.clear();//记得清空
    //最小值,维护单调队列,在窗口内按大小纳入,窗口外踢出(pop_front),新进的小于大的把大的擦掉(pop_back)
    for (int i = 0; i < n; i ++ ){
        while(!D.empty()&&D.front().pos<i-k+1){
            D.pop_front();//不在窗口,弹出
        }
        while(!D.empty()&&D.back().num>N[i]){
            D.pop_back();
        }
        D.push_back({N[i],i});
        if(i>=k-1)cout << D.front().num<<" ";
    }    
    cout << endl;  
    D.clear();//记得清空
    //最大值,维护单调队列,在窗口内按大小纳入,窗口外踢出(pop_front),新进的大于小的把小的擦掉(pop_back)
    for (int i = 0; i < n; i ++ ){
        while(!D.empty()&&D.front().pos<i-k+1){
            D.pop_front();//不在窗口,弹出
        }
        while(!D.empty()&&D.back().num<N[i]){//这里是比较数字
            D.pop_back();
        }
        D.push_back({N[i],i});
        if(i>=k-1)cout << D.front().num<<" ";
    }
  
    return 0;
}
posted @ 2025-07-26 10:30  .N1nEmAn  阅读(9)  评论(0)    收藏  举报