Description
Given a sequence, {A1, A2, ..., An} which is guaranteed A1 > A2, ..., An, you are to cut it into three sub-sequences and reverse them separately to form a new one which is the smallest possible sequence in alphabet order.
The alphabet order is defined as follows: for two sequence {A1, A2, ..., An} and {B1, B2, ..., Bn}, we say {A1, A2, ..., An} is smaller than {B1, B2, ..., Bn} if and only if there exists such i ( 1 ≤ i ≤ n) so that we have Ai < Bi and Aj = Bj for each j < i.
Input
The first line contains n. (n ≤ 200000)
The following n lines contain the sequence.
Output
output n lines which is the smallest possible sequence obtained.
Sample Input
5
10
1
2
3
4
Sample Output
1
10
2
4
3
Hint
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std; int n,k,pos,a[],b[],c[],sa[],rk[],tmp[]; int cmp(int i,int j)
{
if(rk[i]!=rk[j]) return rk[i]<rk[j];
int ri=i+k<=n?rk[i+k]:-;
int rj=j+k<=n?rk[j+k]:-;
return ri<rj;
} int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
{
scanf("%d",&a[i]);
b[n-i]=a[i];
}
for(int i=;i<n;i++)
{
sa[i]=i;
rk[i]=b[i];
}
sa[n]=n;
rk[n]=-;
for(k=;k<=n;k<<=)
{
sort(sa,sa+n+,cmp);
tmp[sa[]]=;
for(int i=;i<=n;i++)
{
tmp[sa[i]]=tmp[sa[i-]]+cmp(sa[i-],sa[i]);
}
for(int i=;i<=n;i++)
{
rk[i]=tmp[i];
}
}
sort(sa,sa+n+,cmp);
for(int i=;i<=n;i++)
{
if(sa[i]!=&&sa[i]!=&&sa[i]!=n)
{
pos=sa[i];
break;
}
}
int len=n-pos;
int cnt=;
for(int i=n;i>=len+;i--)
{
c[cnt++]=a[i];
}
for(int i=cnt;i<cnt*;i++)
{
c[i]=c[i-cnt];
}
n=cnt*;
for(int i=;i<n;i++)
{
sa[i]=i;
rk[i]=c[i];
}
sa[n]=n;
rk[n]=-;
for(k=;k<=n;k<<=)
{
sort(sa,sa+n+,cmp);
tmp[sa[]]=;
for(int i=;i<=n;i++)
{
tmp[sa[i]]=tmp[sa[i-]]+cmp(sa[i-],sa[i]);
}
for(int i=;i<=n;i++)
{
rk[i]=tmp[i];
}
}
for(int i=len;i>=;i--)
{
printf("%d\n",a[i]);
}
sort(sa,sa+n+,cmp);
for(int i=;i<=n;i++)
{
if(sa[i]+n/<n&&sa[i]!=)
{
for(int j=sa[i];j<=sa[i]+n/-;j++)
{
printf("%d\n",c[j]);
}
break;
}
}
}