见代码注释
#include<bits/stdc++.h>
using namespace std;
int a[1000100],r,n;
stack<int>sk;
int main(){
cin>>n;r=n;
for(int i=1;i<=n;i++){
int x;cin>>x;//输入
sk.push(x);//入栈
a[x]++;//入栈标记
while(sk.size()&&r<=sk.top()){//检查当前最大的是否入栈
while(a[r])r--;//更新最右端
cout<<sk.top()<<' ';//输出
sk.pop();//出栈
}
}
}