Introduction to Monotonic Stack
Monotonic stack, the elements in the stack are monotonically increasing or monotonically decreasing.
If a stack is monotonically increasing, it is required to monotonically increase from the top of the stack to the bottom of the stack:
When the element x to be pushed onto the stack is greater than the top element on the stack, all elements smaller than x need to be popped first, and then x is pushed onto the stack.
When the element x to be pushed onto the stack is smaller than the top element on the stack, push x directly onto the stack.
while (stk.size() && x > stk.top()) {
stk.pop();
}
stk.push(x);
P5788 [Template] Monotonic stack
Topic link: https://www.luogu.com.cn/problem/P5788
According to the complexity, we have to find an O(n) algorithm. The complexity of the brute force traversal from left to right is O(n^2)
Try to traverse from right to left, because you are looking for the first number larger than it on the right of each number, so once the number x on the left is greater than the number y on the right, then y is useless (because y is smaller than x, Y will never be used). Just pop y directly at this time.
By analogy, all numbers smaller than x are popped up. At this time, the top element of the stack is the first element to the right of x that is larger than x.
#include <bits/stdc++.h>
using namespace std;
const int N = 3e6 + 5;
stack<int> stk;
int a[N], f[N];
int main(void)
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
// 从右向左
for (int i = n; i >= 1; i--) {
// 如果当前元素大于栈顶元素,说明栈顶元素没用了
while (stk.size() && a[stk.top()] <= a[i]) {
stk.pop();
}
// 当前栈顶元素就是第一个比他大的元素
f[i] = (stk.empty() ? 0 : stk.top());
stk.push(i);
}
for (int i = 1; i <= n; i++) {
printf("%d ", f[i]);
}
puts("");
return 0;
}