单调栈
栈:先入后出。(限定仅在表尾进行插入和删除操作的线性表)
单调栈的应用——查询一个数左端或右端最近的一个数(最大或者最小)。
上边那个题的解释:
要求查询左边最近比它小的数。利用单调的性质如果在加入一个数后由于查询的是比他小的数所以在一个数入栈前,从栈顶开始向下所有大于等于这个数的数值一定不会在以后查询使用,所以将他们退栈。这样栈中数值为一个单调的序列。整个算法时间复杂度O(n)。
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int stk[N],tail=0;//栈尾
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
while(tail&&stk[tail]>=x) tail--;
if(tail==0) cout<<-1<<" ";
else cout<<stk[tail]<<" ";
stk[++tail]=x;
}
}