基于hash的LCP算法;
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define maxn 40010 5 using namespace std; 6 7 const int x=123; 8 int n,m,pos; 9 unsigned long long h[maxn],xp[maxn],hash[maxn]; 10 int rank[maxn]; 11 12 bool cmp(const int &a,const int &b) 13 { 14 return hash[a]<hash[b]||hash[a]==hash[b]&&a<b; 15 } 16 17 int possible(int l) 18 { 19 int c=0; 20 pos=-1; 21 for(int i=0;i<n-l+1;i++) 22 { 23 rank[i]=i; 24 hash[i]=h[i]-h[i+l]*xp[l]; 25 } 26 sort(rank,rank+n-l+1,cmp); 27 for(int i=0;i<n-l+1;i++) 28 { 29 if(i==0||hash[rank[i]]!=hash[rank[i-1]])c=0; 30 if(++c>=m)pos=max(pos,rank[i]); 31 } 32 return pos>=0; 33 } 34 35 int main() 36 { 37 char s[maxn]; 38 while(scanf("%d",&m)&&m) 39 { 40 scanf("%s",s); 41 n=strlen(s); 42 h[n]=0; 43 for(int i=n-1;i>=0;i--) 44 h[i]=h[i+1]*x+(s[i]-'a'); 45 xp[0]=1; 46 for(int i=1;i<=n;i++)xp[i]=xp[i-1]*x; 47 if(!possible(1))puts("none"); 48 else 49 { 50 int l=1,r=n+1; 51 while(l+1<r) 52 { 53 int mid=(r+l)>>1; 54 if(possible(mid))l=mid; 55 else r=mid; 56 } 57 possible(l); 58 printf("%d %d ",l,pos); 59 } 60 } 61 return 0; 62 }