跳到正文

个人记录

单调栈

LawrenceSivan约 1 分钟
原文
文章信息与版本

文章信息

发布
2021年1月8日
收录
2026年7月16日
更新
2026年11月15日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
const int N = 3000005;
int n, a[N], stk[N], ans[N], top;
signed main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%d", a + i);
    for (int i = n; i; --i) {
        while (a[stk[top]] <= a[i] && top) -- top;
        ans[i] = stk[top];
        stk[++ top] = i;
    }
    for (int i = 1; i <= n; ++i) printf("%d ", ans[i]);
    return 0;
}
原文