题目链接:
P5788 【模板】单调栈 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)https://www.luogu.com.cn/problem/P5788
题目描述 :
找个数列中每一个元素右边第一个比本身大的那个数,输出其下标。找不到则输出0;
思路:
可以用单调栈来实现。
手动模拟一个单调递减的栈,栈存储的是下标,若栈不为空,则栈顶元素便是我们想要的那个数的下标。
while (!st.empty() && a[i] >= a[st.top()])st.pop();
if (!st.empty()) ans.push_back(st.top());
else ans.push_back(0);
st.push(i);
由于题目要求的是找右边的元素,那么从头遍历数组的方法显然是不行的,因此我们需要从末尾遍历整个数组。
注意将得到的结果存储到另一个数组里面,再倒序输出即可。
AC代码:
#include <bits/stdc++.h>
using namespace std;
stack<int> st;
int const N = 3000010;
int a[N];
vector<int > ans;
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = n; i >= 1; i--)
{
while (!st.empty() && a[i] >= a[st.top()])st.pop();
if (!st.empty()) ans.push_back(st.top());
else ans.push_back(0);
st.push(i);
}
for (int i = ans.size() - 1; i >= 0; i--) cout << ans[i] << ' ';
return 0;
}