#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
cin>>n;
int a[n]; // массив для перестановки из n чисел
for (int i = 0; i < n; i++) cin>> a[i];
for (int i = n - 2; i >= 0; i--) {
if (a[i] < a[i+1]){
int min = i + 1; // индекс минимального элемента
for (int j = i + 2; j < n; j++) {
if (a[j] > a[i] && a[j] < a[min]) min = j;
}
swap(a[i], a[min]);
reverse(&a[i+1], &a[n]);
break;
}
if (i == 0) reverse(&a[i], &a[n]);
}
for (int i = 0; i < n; i++) cout << a[i] << " ";
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8YWxnb3JpdGhtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKaW50IG1haW4oKSB7CglpbnQgbjsKCWNpbj4+bjsKCWludCBhW25dOyAvLyDQvNCw0YHRgdC40LIg0LTQu9GPINC/0LXRgNC10YHRgtCw0L3QvtCy0LrQuCDQuNC3IG4g0YfQuNGB0LXQuwoJZm9yIChpbnQgaSA9IDA7IGkgPCBuOyBpKyspIGNpbj4+IGFbaV07Cglmb3IgKGludCBpID0gbiAtIDI7IGkgPj0gMDsgaS0tKSB7IAoJCWlmIChhW2ldIDwgYVtpKzFdKXsKCQkJaW50IG1pbiA9IGkgKyAxOyAvLyDQuNC90LTQtdC60YEg0LzQuNC90LjQvNCw0LvRjNC90L7Qs9C+INGN0LvQtdC80LXQvdGC0LAgCgkJCWZvciAoaW50IGogPSBpICsgMjsgaiA8IG47IGorKykgewoJCQkJaWYgKGFbal0gPiBhW2ldICYmIGFbal0gPCBhW21pbl0pIG1pbiA9IGo7CgkJCX0KCQkJc3dhcChhW2ldLCBhW21pbl0pOwoJCQlyZXZlcnNlKCZhW2krMV0sICZhW25dKTsKCQkJYnJlYWs7CgkJfQoJCWlmIChpID09IDApIHJldmVyc2UoJmFbaV0sICZhW25dKTsKCX0KCWZvciAoaW50IGkgPSAwOyBpIDwgbjsgaSsrKSBjb3V0IDw8IGFbaV0gPDwgIiAiOwoJcmV0dXJuIDA7Cn0=