题解 P4051 【[JSOI2007]字符加密】

· · 题解

不会后缀数组的,字符串Hash是个好的算法,可以在 O(n\log^2n) 的时间内完成后缀数组所求的sa[].

具体来说利用字符串Hash,在排序的时候不用 O(len) 比较,而是换成二分查找最远的一个字符串相等的位置.即若现在要比较同一个字符串的两个不同的位置 x,y 为起点,长度为 l 的字符串,找到一个最大的 d 满足 str[x..x+d-1]==str[y..y+d-1],然后再比较下一个字符 str[x+d] 与 str[y+d] 的大小.

对于这道题,将字符串复制一遍,直接排序,cmp函数换成二分就可以了,时间复杂度 O(n\log^2n).

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline char getch(){
    static char buf[10000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,10000,stdin),p1==p2)?EOF:*p1++;
}
#define Getc getch
inline ll read(){
    ll s=0,f=1;char ch=Getc();
    while(ch<'0'||ch>'9')f=(ch=='-'?-1:1),ch=Getc();
    while(ch>='0'&&ch<='9')s=s*10+ch-'0',ch=Getc();
    return s*f;
}
typedef unsigned long long llu;
const int MaxN=100000+5;
const int seed=131;
int pos[MaxN];
char s[MaxN*2];
llu Hash[MaxN*2],Pow[MaxN*2];
int n,N;
llu getHash(int l,int r){return Hash[r]-Hash[l-1]*Pow[r-l+1];}
bool cmp(int x,int y){
    int l=1,r=n,Ans=0;
    while(l<=r){
        int mid=(l+r)>>1;
        if(getHash(x,x+mid-1)==getHash(y,y+mid-1)){
            Ans=mid;
            l=mid+1;
        }else r=mid-1;
    }
    return s[x+Ans]<s[y+Ans];
}
int main(){
    scanf("%s",s+1);n=strlen(s+1);N=2*n;
    for(int i=1;i<=n;i++)s[i+n]=s[i];
    Pow[0]=1;
    for(int i=1;i<=N;i++){
        Pow[i]=Pow[i-1]*seed;
        Hash[i]=Hash[i-1]*seed+s[i];
    }
    for(int i=1;i<=n;i++)pos[i]=i;
    sort(pos+1,pos+n+1,cmp);
    for(int i=1;i<=n;i++)putchar(s[pos[i]+n-1]);
    puts("");
    return 0;
}