#include <fstream>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
ifstream f("scmax.in");
ofstream g("scmax.out");
vector<int> v, poz/*, l*/;
int n;
struct Element {
int lungime_max, poz_elem, val;
};
vector<Element> arbInt;
Element query(int nod, int st, int dr, int val_prec, int pos, int val_gasit)
{
Element q;
q.lungime_max = -1;
q.poz_elem = -1;
q.val = -1;
if (st <= dr && arbInt[nod].val != 0)
{
//int arbVal = arbInt[nod].val;
if (arbInt[nod].lungime_max <= val_gasit)
return q;
if (arbInt[nod].val > val_prec)
return arbInt[nod];
int mij = st + (dr - st) / 2;
if (st < dr)
{
Element fHalf = q, sHalf = q;
if (pos < mij)
fHalf = query(nod << 1, st, mij, val_prec, pos, val_gasit);
if (fHalf.lungime_max == -1 || fHalf.lungime_max < arbInt[(nod << 1) + 1].lungime_max)
sHalf = query((nod << 1) + 1, mij + 1, dr, val_prec, pos, fHalf.lungime_max);
if (fHalf.lungime_max >= sHalf.lungime_max)
return fHalf;
return sHalf;
}
}
return q;
}
void update(int nod, int st, int dr, int pos, int valoare)
{
if (st == dr)
{
Element L_max = query(1, 1, n, v[st], pos, 0);
if (L_max.lungime_max != -1)
arbInt[nod].lungime_max = L_max.lungime_max + 1;
else
arbInt[nod].lungime_max = 1;
arbInt[nod].poz_elem = st;
arbInt[nod].val = v[st];
poz[pos] = L_max.poz_elem;
//l[pos] = arbInt[nod].lungime_max;
return;
}
int mij = st + (dr - st) / 2;
if (pos <= mij)
update(nod << 1, st, mij, pos, valoare);
else
update((nod << 1) + 1, mij + 1, dr, pos, valoare);
if (arbInt[nod << 1].lungime_max > arbInt[(nod << 1) + 1].lungime_max)
arbInt[nod] = arbInt[nod << 1];
else if (arbInt[nod << 1].lungime_max == arbInt[(nod << 1) + 1].lungime_max
&& arbInt[nod << 1].val > arbInt[(nod << 1) + 1].val)
arbInt[nod] = arbInt[nod << 1];
else
arbInt[nod] = arbInt[(nod << 1) + 1];
}
void scmax()
{
poz[n] = -1;
update(1, 1, n, n, 1);
for (int i = n - 1; i > 0; --i)
{
update(1, 1, n, i, 1);
//cout << i << " ";
}
}
int main()
{
f >> n;
poz.resize(n + 1);
v.resize(n + 1);
//l.resize(n + 1);
arbInt.resize(4 * n + 1);
for (int i = 1; i <= n; ++i)
f >> v[i];
scmax();
/*for (int j = 1; j < arbInt.size(); ++j)
cout << arbInt[j].lungime_max << " " << arbInt[j].val << "\n";
cout << "\n";*/
int lg = arbInt[1].lungime_max, poz_max = arbInt[1].poz_elem;
g << lg << "\n";
while(poz_max != -1)
{
g << v[poz_max] << " ";
poz_max = poz[poz_max];
}
return 0;
}