
//#include <bits/stdc++.h>
#include <queue>
#include <deque>
#include <vector>
#include <stdio.h>
using namespace std;
// ================= 代码实现开始 =================
// A:长度为n的数组,下标从0开始,为题中所给1到n的排列
// 返回值:返回一个长度为n的数组,表示所求序列
vector<int> getAnswer(int n, vector<int> A) {
typedef priority_queue<int, vector<int>,less<int> > Heap; //大根堆
Heap heap;
// int t[n] ;
vector<int> ans,t; //t储存未进入队列剩余元素的最大值,ans存储结果列表
deque<int> q; //存储队列
for (int i = 0; i < n; i++) {
heap.push(A[n-i-1]);
t.push_back(heap.top());
}
/* for (int i = 1; i <= n; i++) {
heap.push(A[n-i]);
t[i-1]=heap.top();// 此处为错误的表示方式
}
*/
int j = 0;
for (int i = 0; i < n; i++){
if(q.empty()){
q.push_back(A[j]);j++;}
if( j!=n && q.front()<t[n-j-1] && q.back()<t[n-j-1] ){
do{
q.push_back(A[j]);
j++;
}while(q.back() != t[n-j]);
ans.push_back(q.back());
q.pop_back();
}
else if(q.front()>q.back() ){
ans.push_back(q.front());
q.pop_front();
}
else {
ans.push_back(q.back());
q.pop_back();
}
}
return ans;
}
// ================= 代码实现结束 =================
int main() {
int n;
scanf("%d", &n);
vector<int> a;
for (int i = 0, x; i < n; ++i) {
scanf("%d", &x);
a.push_back(x);
}
vector<int> ans = getAnswer(n, a);
for (int i = 1; i <= n; ++i)
printf("%d%c", ans[i - 1], " \n"[i == n]);
return 0;
}