#include <algorithm>
//#include <fstream>
#include <array>
#include <iostream>
#include <memory>
struct Level;
struct Item
{
Item() : id(0) {}
int id;
std::shared_ptr<Level> level;
std::shared_ptr<Item> next;
std::shared_ptr<Item> prev;
std::shared_ptr<Item> left;
std::shared_ptr<Item> right;
};
struct Level
{
Level() : size(0), nConnUp(0), nConnDown(0) {}
int size;
int nConnUp;
int nConnDown;
std::shared_ptr<Item> first;
std::shared_ptr<Item> last;
};
class Sequence
{
public:
Sequence()
{
for (auto i = 0; i < 100; ++i)
mLevels[i] = std::make_shared<Level>();
}
void add(int i)
{
auto item = std::make_shared<Item>();
item->id = i;
item->prev = mSeqLast;
item->level = mLevels[i];
if (nullptr == mSeqLast)
mSeqFirst = item;
else
mSeqLast->next = item;
item->prev = mSeqLast;
mSeqLast = item;
auto level = mLevels[i];
if (nullptr == level->first)
level->first = item;
else
level->last->right = item;
if (item->prev)
{
if (item->prev->id < item->id)
{
++level->nConnUp;
++item->prev->level->nConnDown;
}
else if (item->prev->id > item->id)
{
++level->nConnDown;
++item->prev->level->nConnUp;
}
}
item->left = level->last;
level->last = item;
++level->size;
}
void sort()
{
std::sort(mLevels.begin(), mLevels.end(), [](std::shared_ptr<Level> a, std::shared_ptr<Level> b) -> bool
{
return a->size > b->size;
});
}
void optimize()
{
for (auto i = 0; i < 100; ++i)
{
auto level = mLevels[i];
if (level->size < level->nConnDown ||
level->size < level->nConnUp)
{
auto item = level->first;
while (nullptr != item)
{
if (item == mSeqFirst)
{
mSeqFirst = item->next;
}
if (item == mSeqLast)
{
mSeqLast = item->prev;
}
if (nullptr != item->prev)
{
if (item->prev->id < item->id)
--item->prev->level->nConnDown;
else if (item->prev->id > item->id)
--item->prev->level->nConnUp;
item->prev->next = item->next;
}
if (nullptr != item->next)
{
if (item->next->id < item->id)
--item->next->level->nConnDown;
else if (item->next->id > item->id)
--item->next->level->nConnUp;
item->next->prev = item->prev;
}
if (nullptr != item->left)
{
item->left->right = item->right;
}
if (nullptr != item->right)
{
item->right->left = item->left;
}
item = item->right;
}
level->size = 0;
level->nConnDown = 0;
level->nConnUp = 0;
level->first = nullptr;
level->last = nullptr;
}
}
}
void print()
{
for (auto i = mSeqFirst; nullptr != i; i = i->next)
{
std::cout << i->id << " ";
}
}
private:
std::shared_ptr<Item> mSeqFirst;
std::shared_ptr<Item> mSeqLast;
std::array<std::shared_ptr<Level>, 100> mLevels;
};
int main()
{
//std::fstream input("input.txt");
auto& input = std::cin;
int num;
input >> num;
Sequence seq;
for (auto i = 0; i < num; ++i)
{
int ai;
input >> ai;
seq.add(ai);
}
seq.sort();
seq.optimize();
seq.print();
return 0;
}