#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> p(n);
for(auto &nx : p){cin >> nx;}
next_permutation(p.begin(),p.end());
set<int> st;
for(int i=1;i<=n;i++){st.insert(i);}
vector<int> res={p[0]};
st.erase(p[0]);
bool fl=true;
for(int i=1;i<n;i++){
if(fl){
int lef=-1;
auto it=st.lower_bound(res.back());
if(it!=st.begin()){
it--;
lef=(*it);
}
if(lef<=p[i]){
res.push_back(p[i]);
st.erase(p[i]);
}
else{
res.push_back(lef);
st.erase(lef);
fl=false;
}
}
else{
auto it=st.lower_bound(res.back());
if(it!=st.begin()){
it--;
}
res.push_back(*it);
st.erase(it);
}
}
for(int i=0;i<n;i++){
if(i){cout << " ";}
cout << res[i];
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFpbigpewogIGludCBuOwogIGNpbiA+PiBuOwogIHZlY3RvcjxpbnQ+IHAobik7CiAgZm9yKGF1dG8gJm54IDogcCl7Y2luID4+IG54O30KICBuZXh0X3Blcm11dGF0aW9uKHAuYmVnaW4oKSxwLmVuZCgpKTsKCiAgc2V0PGludD4gc3Q7CiAgZm9yKGludCBpPTE7aTw9bjtpKyspe3N0Lmluc2VydChpKTt9CgogIHZlY3RvcjxpbnQ+IHJlcz17cFswXX07CiAgc3QuZXJhc2UocFswXSk7CiAgYm9vbCBmbD10cnVlOwogIGZvcihpbnQgaT0xO2k8bjtpKyspewogICAgaWYoZmwpewogICAgICBpbnQgbGVmPS0xOwogICAgICBhdXRvIGl0PXN0Lmxvd2VyX2JvdW5kKHJlcy5iYWNrKCkpOwogICAgICBpZihpdCE9c3QuYmVnaW4oKSl7CiAgICAgICAgaXQtLTsKICAgICAgICBsZWY9KCppdCk7CiAgICAgIH0KCiAgICAgIGlmKGxlZjw9cFtpXSl7CiAgICAgICAgcmVzLnB1c2hfYmFjayhwW2ldKTsKICAgICAgICBzdC5lcmFzZShwW2ldKTsKICAgICAgfQogICAgICBlbHNlewogICAgICAgIHJlcy5wdXNoX2JhY2sobGVmKTsKICAgICAgICBzdC5lcmFzZShsZWYpOwogICAgICAgIGZsPWZhbHNlOwogICAgICB9CiAgICB9CiAgICBlbHNlewogICAgICBhdXRvIGl0PXN0Lmxvd2VyX2JvdW5kKHJlcy5iYWNrKCkpOwogICAgICBpZihpdCE9c3QuYmVnaW4oKSl7CiAgICAgICAgaXQtLTsKICAgICAgfQogICAgICByZXMucHVzaF9iYWNrKCppdCk7CiAgICAgIHN0LmVyYXNlKGl0KTsKICAgIH0KICB9CgogIGZvcihpbnQgaT0wO2k8bjtpKyspewogICAgaWYoaSl7Y291dCA8PCAiICI7fQogICAgY291dCA8PCByZXNbaV07CiAgfQp9Cg==