利用栈来操作,如果当前入栈的元素比栈顶元素大,那这个元素就是栈顶元素右边第一个比栈顶元素大的元素。如果当前元素比栈顶元素小。或者栈为空,那当前元素入栈。
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
const int MAXN = 1e6+10;
int arr[MAXN];
int ans[MAXN];
int main()
{
int N;
cin >> N;
for(int i = 0 ; i < N ; i++)
{
cin >>arr[i];
ans[i]=-1;
}
stack<vector<int> > s;
for(int i = 0 ; i < N ; i++)
{
vector<int> t;
if(!s.empty())
{
while(!s.empty()&&arr[s.top()[0]]<arr[i]){//如果当前元素比栈顶大,那么给栈顶元素记上答案,然后出栈
for(int j = 0 ; j < s.top().size() ; j++){ans[s.top()[j]] = i-s.top()[j];}
s.pop();
}
if(s.empty()){
t.push_back(i);
s.push(t);
continue;
}
if(arr[s.top()[0]] == arr[i]){s.top().push_back(i);}
if(arr[s.top()[0]] > arr[i]){
t.push_back(i);
s.push(t);
}
}
else{
t.push_back(i);
s.push(t);
}
}
for(int i = 0 ;i < N ; i++)
{
cout<<ans[i]<<endl;
}
return 0;
}

京公网安备 11010502036488号