好久没学新算法了,从现在开始努力吧。
花了3天时间看了后缀数组的论文,差不多看明白了,贴上一份应用的代码吧。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <queue>
#include <ctime>
#include <set>
#include <deque>
#include <string>
#define MP make_pair
#define PB push_back
#define SZ(x) ((int)(x).size())
#define REP(i,n) for (int _n=n,i=0; (i)<_n; ++(i))
#define FOR(i,a,b) for (int _b=b,i=(a);i<=_b;++(i))
#define FOREACH(it,c) for ( __typeof((c).begin()) it=(c).begin(),ite=(c).end(); it!=ite; ++it )
int rint() { int x; if(~scanf("%d",&x)) return x; return -1; }
typedef long long LL;
const int inf=~0U>>1;
using namespace std;
const int maxN=200010;
const int maxC=300;
int n,sa[maxN],height[maxN],top[maxN],rank[maxN],tmp[maxN],len1,ans;
string s;
void makesa(){
memset(top,0,sizeof(top));
REP(i,n) top[rank[i]=s[i]]++;
for(int i=1;i<maxN;i++) top[i]+=top[i-1];
REP(i,n) sa[--top[rank[i]]]=i;
for(int len=1;len<n;len<<=1){
int j=0;
REP(i,n){
j=sa[i]-len;
if(j<0) j+=n;
tmp[top[rank[j]]++]=j;
}
sa[tmp[top[0]=0]]=j=0;
for(int i=1;i<n;i++){
if(rank[tmp[i]]!=rank[tmp[i-1]]||rank[tmp[i]+len]!=rank[tmp[i-1]+len])
top[++j]=i;
sa[tmp[i]]=j;
}
memcpy(rank,sa,n*sizeof(int));
memcpy(sa,tmp,n*sizeof(int));
if(j>=n-1) return;
}
}
void calheight(){
int i,j,k;
for(j=rank[height[i=k=0]=0];i<n-1;i++,k++){
while(k>=0&&s[i]!=s[sa[j-1]+k]){
height[j]=(k--);
if((sa[j]<len1&&sa[j-1]>len1)||(sa[j]>len1&&sa[j-1]<len1)) {
//puts("**");
if(ans<height[j]) ans=height[j];
}
j=rank[sa[j]+1];
}
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
#endif
string s1,s2;
while(cin>>s1>>s2){
len1=SZ(s1);
s=s1+"$"+s2;
n=s.size()+1;
ans=0;
makesa();
calheight();
cout<<ans<<endl;
}
return 0;
}