- 单调栈monotonous_stack
- 例题
- 力扣
- 未做
![](https://i-blog.csdnimg.cn/blog_migrate/ebb4811d195de055ea7d80392862abc8.jpeg)
/*Monotone_stack.cpp*/
#include<bits/stdc++.h>
using namespace std;
int val[3000005] = {0};
int stk[3000005];//存的是下标i
int ansr[3000005];
int ansl[3000005];
int top = -1;
//【常用】答案在while外面收集时:逆序找右边的,正序找左边的
//答案在while里面收集时:逆序找左边的,正序找右边的(反过来)
int main(){
int n; cin>>n;
for(int i = 1; i<=n; i++) cin>>val[i];
for(int i = n; i>=0; i--){// 从右到左遍历数组
// 对于每一个元素,先逐个弹出栈顶小于等于它的元素
while(top>-1 && val[i]>=val[stk[top]]) {
ansl[stk[top]] = i;
top--;//维护一个 上小下大 的单调栈
}
if(top>-1) ansr[i] = stk[top];// 如果栈非空,由于上小下大,则栈顶元素就是大于当前元素的最近点
else ansr[i] = 0;// 否则则不存在
stk[++top] = i;//入栈,存入下标
}
for(int i = 1; i<=n; i++) printf("%d ", ansr[i]);
printf("\n");
for(int i = 1; i<=n; i++) printf("%d ", ansl[i]);
return 0;
}
/*
样例
5
1 4 2 3 5
输出
2 5 4 5 0
0 0 2 2 0
*/