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.
The first line contains n. (n ≤ 200000)
The following n lines contain the sequence.
output n lines which is the smallest possible sequence obtained.
5
10
1
2
3
4
1
10
2
4
3
给出一列数字,要求你将这列数分成三段,然后将三段分别翻转,要求使得翻转后的数列字典序最小。
首先将整个数组翻转,构建第一次后缀数组,由于有保证第一个数最大这个条件,所以可以直接根据后缀数组来确定第一个分割点。(因为前面不可能出现与此有公共前缀的子串,但是确定第二个分割点就没有那么直接因为没有这样的性质)确定第二个分割点需要将剩余数列复制一遍粘贴在后部,求第二次后缀数组,只需要保证sa的值在前一半即可。找到断点后按序输出。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long
#define ull unsigned long long
#define rep(i,n) for(int i = 0;i < n; i++)
#define fil(a,b) memset((a),(b),sizeof(a))
#define cl(a) fil(a,0)
#define pb push_back
#define mp make_pair
#define ee 2.7182818
#define PI 3.141592653589793
#define inf 0x3f3f3f3f
#define fi first
#define se second
#define eps 1e-7
#define mod 1000000007ll
#define maxn 200100
using namespace std;
int n, k;
int a[maxn];
int b[maxn];
int rk[maxn], temp[maxn],sa[maxn];
int rrank[maxn+1];
int lcp[maxn];
bool compare_sa(int i, int j){
if(rk[i] != rk[j]) return rk[i] < rk[j];
else {
int ri = i+k<=n?rk[i+k]:-1;
int rj = j+k<=n?rk[j+k]:-1;
return ri < rj;
}
}
void construct_sa(int a[], int n, int sa[]){
for(int i=0; i<=n; i++) {
sa[i] = i;
rk[i] = i1;
}
for(k=1; k<=n; k*=2){
sort(sa, sa+n+1, compare_sa);
temp[sa[0]] = 0;
for(int i=1; i<=n; i++){
temp[sa[i]] = temp[sa[i-1]] + (compare_sa(sa[i-1], sa[i])?1:0);
}
for(int i=0; i<=n; i++) rk[i] = temp[i];
}
}
void construct_lcp(int a[],int n,int *sa,int *lcp)
{
for(int i=0;i<=n;++i)
{
rrank[sa[i]]=i;
}
int h=0;
lcp[0]=0;
for(int i=0;iint j=sa[rrank[i]-1];
if(h>0) h--;
for(;j+hif(a[j+h]!=a[i+h]) break;
}
lcp[rrank[i]-1]=h;
}
}
int main(void)
{
cin>>n;
for(int i=0;iscanf("%d",&b[i]);
reverse_copy(b,b+n,a);
construct_sa(a,n,sa);
int p1;
for(int i=0;iif(p1>=1&&n-p1>=2) break;
}
int m=n-p1;
reverse_copy(b+p1,b+n,a);
reverse_copy(b+p1,b+n,a+m);
construct_sa(a,m*2,sa);
int p2;
for(int i=0;i<=2*m;++i)
{
p2=p1+m-sa[i];
if(p2-p1>=1&&n-p2>=1) break;
}
reverse(b,b+p1);
reverse(b+p1,b+p2);
reverse(b+p2,b+n);
for(int i=0;iprintf("%d\n",b[i]);
return 0;
}