题目:
在数组中求每个元素之后第一个比它大的数的下标
题解:
使用递减单调栈来存储下标,从后往前遍历数组
代码:
#include<bits/stdc++.h>
using namespace std;
#define f(i,n) for(int i=1;i<=n;++i)
const int N = 3e6 + 1;
typedef long long ll;
ll a[N];
ll ans[N];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
stack<ll>st;//单调递减栈,装元素下标
memset(a, 0, sizeof(a));//全部用0覆盖
ll n; cin >> n;
f(i, n)
cin >> a[i];
for (int i = n; i >= 0; --i) {
while (!st.empty() && a[i] >= a[st.top()])
st.pop();
if (!st.empty())
ans[i] = st.top();//发现第一次比它小的元素的下标
st.push(i);
//cout << st.top() << " ";
}
for (int i = 1; i <= n; ++i)
printf("%d"" ", ans[i]);
return 0;
}