Mr. Kim is a professional programmer. Recently he wants to design a new editor which has as many functions as possible. Most editors support a simple search function that finds one occurrence (or all occurrences
successively) of a query pattern string in the text.
He observed that the search function in commercial editors does nothing if no query pattern is given. His idea of a new search function regards each substring of the given text as a query
pattern string itself and his new function finds another occurrence in the text. The problem is that there can be occurrences of many substrings in the text. So, Mr. Kim decides that the new function finds only occurrences of the longest
substring in the text in order to remedy the problem. A formal definition of the search function is as follows:
Given a text string S , find the longest substring in text string S such that the substring appears at least twice. The two occurrences are allowed
to overlap.
Input
Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the
input. For each test case, a text string S is given in one line. For every string, the length is less than or equal to 5,000 and the alphabet is
the set of lowercase English characters.
Output
Your program is to write to standard output. Print exactly one line for each test case. Print the length of the longest substring in text string S such that the substring appears
at least twice.
Sample Input
3 abcdefghikjlmn abcabcabc abcdabcabb
Sample Output
0 6 3 做这么多后缀数组题以来,这个应该是最水的了吧 ac代码 0ms过#include<stdio.h> #include<string.h> #include<algorithm> #include<iostream> #define min(a,b) (a>b?b:a) #define max(a,b) (a>b?a:b) #define N 1000005 using namespace std; char str[5010]; int sa[5010],Rank[5010],rank2[5010],height[5010],c[5010],*x,*y,s[5010],k; void cmp(int n,int sz) { int i; memset(c,0,sizeof(c)); for(i=0;i<n;i++) c[x[y[i]]]++; for(i=1;i<sz;i++) c[i]+=c[i-1]; for(i=n-1;i>=0;i--) sa[--c[x[y[i]]]]=y[i]; } void build_sa(char *s,int n,int sz) { x=Rank,y=rank2; int i,j; for(i=0;i<n;i++) x[i]=s[i],y[i]=i; cmp(n,sz); int len; for(len=1;len<n;len<<=1) { int yid=0; for(i=n-len;i<n;i++) { y[yid++]=i; } for(i=0;i<n;i++) if(sa[i]>=len) y[yid++]=sa[i]-len; cmp(n,sz); swap(x,y); x[sa[0]]=yid=0; for(i=1;i<n;i++) { if(y[sa[i-1]]==y[sa[i]]&&sa[i-1]+len<n&&sa[i]+len<n&&y[sa[i-1]+len]==y[sa[i]+len]) x[sa[i]]=yid; else x[sa[i]]=++yid; } sz=yid+1; if(sz>=n) break; } for(i=0;i<n;i++) Rank[i]=x[i]; } void getHeight(char *s,int n) { int k=0; for(int i=0;i<n;i++) { if(Rank[i]==0) continue; k=max(0,k-1); int j=sa[Rank[i]-1]; while(s[i+k]==s[j+k]) k++; height[Rank[i]]=k; } } int main() { int t; scanf("%d",&t); while(t--) { scanf("%s",str); int ans=0; int n=strlen(str); build_sa(str,n+1,128); getHeight(str,n); for(int i=1;i<=n;i++) ans=max(ans,height[i]); printf("%d\n",ans); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。