首页 > 其他 > 详细

单调栈

时间:2020-06-11 02:11:43      阅读:33      评论:0      收藏:0      [点我收藏+]

1.何为单调栈

     满足单调性的栈结构

2. 如何使用栈结构

     将一个元素插入栈中时,为了维护栈的单调性,需要保障将该元素插入栈顶以后

栈满足单调性的前期下弹出最少的元素。

      例如:栈中自顶向下的元素依次为 1 3 5 10 30 50,插入20时为了满足单调性,需要

依次弹出1 3  5 10,操作后栈变为  20 30 50.

  使用伪码描述:

1 insert x
2 while !sta.empty() && sta.top <x
3         sta.pop()
4 sta.push(x)

 

 

技术分享图片

 

 

 

技术分享图片
#include<iostream>
#include<stack>
using namespace std;

const int N = 100010;
int stk[N], tt;
int main(){
    int n; cin>>n;
    while(n--){
        int x; 
        cin>>x;
        while(tt && stk[tt]>=x) tt--;
        (tt==0) ? cout<<"-1"<<" " : cout<<stk[tt]<<" ";
        stk[++tt] = x;
    }
    return 0;
} 
View Code

 使用STL:

技术分享图片
 1 #include<iostream>
 2 #include<stack>
 3 using namespace std;
 4 
 5 stack<int> s;
 6 int main(){
 7     int n;
 8     cin>>n;
 9     while(n--){
10         int x; cin>>x;
11         while(!s.empty() && s.top() >= x) 
12             s.pop();
13         if(s.empty()) cout<<"-1 ";
14         else cout<<s.top()<<" ";
15         s.push(x);
16     }
17     return 0;
18 }
View Code

 

单调栈

原文:https://www.cnblogs.com/wsl96/p/13089822.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!