单调栈模板

定义:栈内元素单调递增或者单调递减的栈,单调栈只能在栈顶操作。
应用:
单调栈解决的是以某个值为最小(最大)值的最大区间,实现方法是:求最小值(最大值)的最大区间,维护一个递增(递减)的栈,当遇到一个比栈顶小的值的时候开始弹栈,弹栈停止的位置到这个值的区间即为此值左边的最大区间;同时,当一个值被弹掉的时候也就意味着比它更小(更大)的值来了,也可以计算被弹掉的值得右边的最大区间。

注:单调栈是维护某个值是最小值或最大值的最大区间。也就是说每一个值都是最小值,只不过是在自己的区间

在这里插入图片描述

完整代码:

#include<iostream>
#include<cstdio>
using namespace std;
const int n=5;
int a[n+1];
struct st{
 int num;
 int l;
 int r;
} s[n+1];
int top=0;
void pop()
{
 s[top-1].r=s[top].r;
 printf("%d %d %d\n",s[top].l,s[top].r,s[top].num);
 //以后程序计算都这个里面 
}
int main()
{   
    for(int i=1;i<=n;i++)
    {  
    scanf("%d",&a[i]);
    st temp={a[i],i,i};
       while(top!=0&&a[i]<s[top].num)
       {           
   pop();//只有来了个小的数,在被迫出栈,才更新左区间
            temp.l=s[top].l;
   top--;  
    }
    //把temp入栈 
    top++; 
    s[top].num=temp.num;
    s[top].l=temp.l;
    s[top].r=temp.r;
  
    }
    while(top>0)
    {
    pop(); 
    top--;
    }
 return 0;
}
发布了9 篇原创文章 · 获赞 0 · 访问量 114

猜你喜欢

转载自blog.csdn.net/hwdn3000/article/details/104419695