https://ac.nowcoder.com/acm/contest/22669/A
维护一个后缀最大值,当前的值等于后缀最大时直接输出,栈顶的元素大于等于后缀最大时也直接输出,否则压进栈里。
#include<bits/stdc++.h>
#define endl '\n'
#define pii pair<int,int>
using namespace std;
using ll = long long;
const int maxn = 1e7+3;
int a[maxn];
int suf_max[maxn];
stack<int>q;
void solve()
{
int n; cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=n;i>=1;i--)
suf_max[i]=max(suf_max[i+1],a[i]);
for(int i=1;i<=n;i++)
{
while(!q.empty()&&q.top()>=suf_max[i])
{
cout<<q.top()<<' ';
q.pop();
}
if(a[i]==suf_max[i])
{
cout<<a[i]<<' ';
// q.pop();
}
else
{
q.push(a[i]);
}
}
while(!q.empty())
{
cout<<q.top()<<' ';
q.pop();
}
return ;
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int T; T=1;
while(T--)
solve();
return 0;
}