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
{10, 1, 2, 3, 4} -> {10, 1 | 2 | 3, 4} -> {1, 10, 2, 4, 3}
题意:给你一个串,让你把该串分成三部分然后将每一部分翻转,输出翻转后字典序最小的串(注意题中给出串中的第一个数是最大的)
思路:由于第一个数是最大的,所以第一段的分割点就是将串翻转然后求翻转后数组的sa数组(最小后缀),但是第二段不能用这种方法,因为第二段的首字符不满足最大这个要求,所以需要用别的方法,将剩下的数组(翻转后的)后面再接上本身,然后求最小后缀即为第二段,然后剩下的是第三段,输出即可
ac代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=200010;
int n,k;
int rank1[maxn*2],tmp[maxn*2],sa[maxn*2],rev[maxn*2];
int str[maxn],ans[maxn];
bool compare_sa(int i,int j){
if(rank1[i]!=rank1[j]) return rank1[i]<rank1[j];
else{
int ri=i+k<=n? rank1[i+k]:-1;
int rj=j+k<=n? rank1[j+k]:-1;
return ri<rj;
}
}
void construct_sa(int *str1){
for(int i=0;i<=n;i++){
sa[i]=i;
rank1[i]=i<n? str1[i]:-1;
}
for(k=1;k<=n;k*=2){
sort(sa,sa+n+1,compare_sa);
tmp[sa[0]]=0;
for(int i=1;i<=n;i++){
tmp[sa[i]]=tmp[sa[i-1]]+(compare_sa(sa[i-1],sa[i])?1:0);
}
for(int i=0;i<=n;i++) rank1[i]=tmp[i];
}
}
int main(){
int nn;
scanf("%d",&nn);
for(int i=0;i<nn;i++) scanf("%d",&str[i]);
for(int i=0;i<nn;i++) rev[nn-1-i]=str[i];
n=nn;construct_sa(rev);
int pos1,pos2;
for(int i=0;i<nn;i++){
pos1=nn-sa[i];
if(pos1>=1&&nn-pos1>=2) break;
}
for(int i=pos1-1;i>=0;i--) printf("%d\n",str[i]);
int kk=0;
for(int i=nn-1;i>=pos1;i--) rev[kk++]=str[i];
for(int i=nn-1;i>=pos1;i--) rev[kk++]=str[i];
n=kk;
construct_sa(rev);
for(int i=0;i<=n;i++){
pos2=pos1+n/2-sa[i];
if(pos2-pos1>=1&&nn-pos2>=1) break;
}
for(int i=pos2-1;i>=pos1;i--) printf("%d\n",str[i]);
for(int i=nn-1;i>=pos2;i--) printf("%d\n",str[i]);
return 0;
}