<算法笔记7.13>栈与队列&&单调栈&&单调队列

栈与队列

什么是栈(Stack)

栈其实就是一种数据结构 - 先进后出(先入栈的数据后出来,最先入栈的数据会被压入栈底)

什么是队列(Queue)

只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有 - 先进先出。

数组模拟栈

用top表示栈顶所在的索引。初始时,top = -1。表示没有元素。

push x :栈顶所在索引往后移动一格,然后放入x。st[++top] = x。

pop : top 往前移动一格。top–。

empty :top 大于等于 0 栈非空,小于 0 栈空。top == -1 ? “YES” : “NO”

query : 返回栈顶元素。st[top]

#include <iostream>
#include <string.h>

using namespace std;
const int N=1e5+10;
int st[N];
int top=-1;
int n;
int main(){
    scanf("%d",&n);
    while(n--){
        string s;
        cin>>s;
        if(s=="push"){
            int a;
            cin>>a;
            st[++top]=a;
        }
        else if(s=="pop"){
            top--;
        }
        else if(s=="empty"){
            cout<<(top==-1?"YES":"NO")<<endl;
        }
        else if(s=="query") cout<<st[top]<<endl;
    }
}

数组模拟数列

#include <iostream>

#include <string.h>
using namespace std;

const int N=1e5+10;
int qu[N];
int hh=0,tt=-1;
int m;

int main(){
    scanf("%d",&m);
    while(m--){
        string s;
        cin>>s;
        if(s=="push"){
            int a;
            cin>>a;
            qu[++tt]=a;
        }
        else if(s=="pop"){
            hh++;
        }
        else if(s=="empty"){
            if(tt>=hh) cout<<"NO"<<endl;
            else cout<<"YES"<<endl;
        }
        else if(s=="query") cout<<qu[hh]<<endl;
    }
   

单调栈

AcWing 830.单调栈
在这里插入图片描述

#include <iostream>
#include <stdio.h>
using namespace std;
const int N=1e5+10;
int st[N];
int tt=0;
int n;
int main(){
    scanf("%d",&n);
    while(n--){
        int x;
        scanf("%d",&x);
        while(tt&&st[tt]>=x) tt--;
        if(!tt) printf("-1 ");
        else printf("%d ",st[tt]);
        st[++tt]=x;
    }
    return 0;
}

单调队列

AcWing 154.滑动窗口
图解

#include <iostream>
using namespace std;
const int N=1e6+10;
int a[N],q[N];

int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;i++)
       scanf("%d",&a[i]);
    
    int hh = 0, tt = -1;
    for(int i=0;i<n;i++)
    {
        if(hh<=tt&&i-k+1>q[hh])hh++;
        while(hh<=tt&&a[q[tt]]>=a[i])tt--;
        q[++tt]=i;
        if(i>=k-1)printf("%d ",a[q[hh]]);
    }
    puts("");
    
     hh = 0, tt = -1;
    for(int i=0;i<n;i++)
    {
        if(hh<=tt&&i-k+1>q[hh])hh++;
        while(hh<=tt&&a[q[tt]]<=a[i])tt--;
        q[++tt]=i;
        if(i>=k-1)printf("%d ",a[q[hh]]);
    }
    puts("");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值