单调栈学习笔记

· · 个人记录

满足单调性的栈结构。

#include <bits/stdc++.h>
using namespace std;

inline int read()
{
    int x=0; int f=1; char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}

const int MAXN = 3000005;
int val[MAXN],st[MAXN],ans[MAXN];
int n,top;

int main(int argc, char const *argv[])
{
    n=read();
    for(int i=1; i<=n; i++) val[i]=read();
    for(int i=1; i<=n; i++)
    {
        while(val[i]>val[st[top]] && top)
            ans[st[top--]]=i;
        st[++top]=i;
    }
    for(int i=1; i<=n; ++i)
        printf("%d ",ans[i]);
    return 0;
}