一. AcWing830_单调栈
二. 理论
- 每次将当前元素和栈顶比较, 若栈顶元素>=当前数,则栈顶永远不可能是答案,出栈
- 直到栈顶元素<当前数,将当前数入栈
- 每次栈顶就是当前数嘴边小于他的数最近的
三. 代码
#include<iostream>
#include<cstdio>
using namespace std;
namespace Question
{
const int N=1e5+10;
int n;
}
using namespace Question;
namespace Stack
{
int stk[N], top;
}
using namespace Stack;
signed main()
{
cin>>n;
while(n--)
{
int x;
scanf("%d", &x);
while(top&&stk[top]>=x) top--;//栈顶元素比当前数大, 永远也不可能是答案, 弹出
if(top) printf("%d ", stk[top]);
else printf("-1 ");
stk[++top]=x;//当前元素入栈
}
}