This documentation is automatically generated by online-judge-tools/verification-helper
#define PROBLEM "https://judge.yosupo.jp/problem/cartesian_tree"
#include "template.hpp"
#include "data-structure/cartesian-tree.hpp"
int main(){
cin.tie(nullptr)->sync_with_stdio(false);
int n;
cin >> n;
vector<int> a(n);
for(auto &x:a)cin >> x;
CartesianTree<int,true> ct(a);
auto ans=ct.par;
ans[ct.root]=ct.root;
for(auto x:ans)cout << x << " ";
}
#line 1 "verify/yosupo/tree/cartesian_tree.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/cartesian_tree"
#line 2 "template.hpp"
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
using ll = long long;
using db = long double;
using vi = vector<int>;
using vl = vector<ll>;
using vd = vector<db>;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pdd = pair<db,db>;
const int INF=INT_MAX/2;
const int MOD=998244353;
const int MOD2=1000000007;
const ll LINF=LLONG_MAX/2;
const db DINF=numeric_limits<db>::infinity();
const db EPS=1e-9;
const db PI=acos(db(-1));
template<class T>
using ordered_set = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
template<class T>
using ordered_multiset = tree<T,null_type,less_equal<T>,rb_tree_tag,tree_order_statistics_node_update>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
mt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());
#line 3 "data-structure/cartesian-tree.hpp"
/**
* Author: Teetat T.
* Date: 2025-02-20
* Description: Cartesian Tree.
*/
template<class T,bool IS_MIN>
struct CartesianTree{
int n;
vector<T> &a;
vector<pair<int,int>> range;
vector<int> lch,rch,par;
int root;
CartesianTree(vector<T> &_a):n((int)_a.size()),a(_a){
range.assign(n,{-1,-1});
lch=rch=par=vector<int>(n,-1);
if(n==1){
range[0]={0,1};
root=0;
return;
}
auto cmp=[&](int i,int j)->bool {
if(IS_MIN)a[i]>a[j]||(a[i]==a[j]&&i<j);
return a[i]<a[j]||(a[i]==a[j]&&i<j);
};
vector<int> st;
for(int i=0;i<n;i++){
while(!st.empty()&&cmp(i,st.back())){
lch[i]=st.back();
st.pop_back();
}
range[i].first=(st.empty()?-1:st.back())+1;
st.emplace_back(i);
}
for(int i=n-1;i>=0;i--){
while(!st.empty()&&cmp(i,st.back())){
rch[i]=st.back();
st.pop_back();
}
range[i].second=(st.empty()?n:st.back())-1;
st.emplace_back(i);
}
for(int i=0;i<n;i++)if(lch[i]!=-1)par[lch[i]]=i;
for(int i=0;i<n;i++)if(rch[i]!=-1)par[rch[i]]=i;
for(int i=0;i<n;i++)if(par[i]==-1)root=i;
}
};
#line 4 "verify/yosupo/tree/cartesian_tree.test.cpp"
int main(){
cin.tie(nullptr)->sync_with_stdio(false);
int n;
cin >> n;
vector<int> a(n);
for(auto &x:a)cin >> x;
CartesianTree<int,true> ct(a);
auto ans=ct.par;
ans[ct.root]=ct.root;
for(auto x:ans)cout << x << " ";
}