分治法:

  • 找到a中最大值push进ans数组
  • 递归最大值右边的子数组
  • push最大值左边的子数组
#include <bits/stdc++.h>
using namespace std;
#define int long long
int n;
vector<int> a;
vector<int> ans;

void make(int l,int r){
    if(l > r)return ;
    int maxn = -1;
    int pos = -1;
    for(int i=l;i<=r;i++){
        if(a[i] > maxn){
            pos = i;
            maxn = a[i];
        }
    }
    ans.emplace_back(maxn);
    make(pos+1,r);
    // make(l,pos-1);
    for(int i=pos-1;i>=l;i--){
        ans.emplace_back(a[i]);
    }
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);cout.tie(nullptr);

    cin >> n;
    for(int i=0;i<n;i++){
        int t;cin >> t;
        a.emplace_back(t);
    }

    make(0,n-1);

    for(int x : ans){
        cout << x << ' ';
    }
    cout << '\n';
    return 0;
}

注意不要递归左边的子数组(当递归右边子数组后,左边的子数组pop顺序就固定了)