【模板】单调栈(P5788)
题意
给定一个长度为 的序列 ,定义 为第 个元素之后第一个严格大于 的元素下标,不存在则为 。输出 。
思路
从右向左维护“严格递减”的单调栈:
- 栈中存储下标,且对应的值严格递减;
- 对于当前位置 ,不断弹出小于等于 的下标,剩余的栈顶即为第一个更大的位置;
- 若栈为空,则 ;
- 处理完后将 入栈继续向左。
时间复杂度 。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include <bits/stdc++.h> using namespace std;
const int N = 3'000'000 + 5; int a[N], ans[N];
int main() { ios::sync_with_stdio(false); cin.tie(nullptr);
int n; cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i];
stack<int> st; for (int i = n; i >= 1; --i) { while (!st.empty() && a[st.top()] <= a[i]) st.pop(); ans[i] = st.empty() ? 0 : st.top(); st.push(i); }
for (int i = 1; i <= n; ++i) { cout << ans[i] << (i == n ? '\n' : ' '); } return 0; }
|