标签:
Write a program that takes a string and returns length of the longest repeated substring. A repeated substring is a sequence of characters that is immediately followed by itself.
For example, given "Mississippi", the longest repeated substring is "iss" or "ssi" (not "issi").
Given "Massachusetts", the longest repeated substring would be either "s" or "t".
Given "Maine", the longest repeated substring is "" (the empty string).
Input
The first line of the input contains a single integer T , the number of test cases.
Each of the following T lines, is exactly one string of lowercase charactors.
The length of each string is at most 50000 characters.
Output
For each test case, print the length of the Longest Repeated Substring.
Sample Input
2 aaabcabc ab
Sample Output
3 0
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 100010; 4 char s[maxn]; 5 int sa[maxn],t[maxn],t2[maxn]; 6 int height[maxn],rk[maxn],c[maxn],n; 7 void build_sa(int m) { 8 int i,*x = t,*y = t2; 9 for(i = 0; i < m; ++i) c[i] = 0; 10 for(i = 0; i < n; ++i) c[x[i] = s[i]]++; 11 for(i = 1; i < m; ++i) c[i] += c[i-1]; 12 for(i = n-1; i >= 0; --i) sa[--c[x[i]]] = i; 13 14 for(int k = 1; k <= n; k <<= 1) { 15 int p = 0; 16 for(i = n-k; i < n; ++i) y[p++] = i; 17 for(i = 0; i < n; ++i) 18 if(sa[i] >= k) y[p++] = sa[i] - k; 19 for(i = 0; i < m; ++i) c[i] = 0; 20 for(i = 0; i < n; ++i) c[x[y[i]]]++; 21 for(i = 1; i < m; ++i) c[i] += c[i-1]; 22 for(i = n-1; i >= 0; --i) sa[--c[x[y[i]]]] = y[i]; 23 swap(x,y); 24 x[sa[0]] = 0; 25 for(p = i = 1; i < n; ++i) 26 if(y[sa[i]] == y[sa[i-1]] && y[sa[i]+k] == y[sa[i-1]+k]) 27 x[sa[i]] = p-1; 28 else x[sa[i]] = p++; 29 if(p >= n) break; 30 m = p; 31 } 32 } 33 void getHeight() { 34 int i,j,k = 0; 35 for(i = 0; i < n; ++i) rk[sa[i]] = i; 36 for(i = 0; i < n; ++i) { 37 if(k) --k; 38 j = sa[rk[i]-1]; 39 while(i + k < n && j + k < n && s[i+k] == s[j+k]) ++k; 40 height[rk[i]] = k; 41 } 42 } 43 int main(){ 44 int kase; 45 scanf("%d",&kase); 46 while(kase--){ 47 scanf("%s",s); 48 n = strlen(s) + 1; 49 build_sa(128); 50 getHeight(); 51 int ret = 0; 52 for(int i = 2; i < n; ++i){ 53 int tmp = height[i]; 54 if(abs(sa[i-1] - sa[i]) == tmp && tmp > ret) ret = tmp; 55 for(int j = i + 1; j < n; ++j){ 56 tmp = min(tmp,height[j]); 57 if(tmp <= ret) break; 58 if(abs(sa[i-1] - sa[i]) == tmp && tmp > ret) ret = tmp; 59 } 60 } 61 printf("%d\n",ret); 62 } 63 return 0; 64 }
ZOJ 3199 Longest Repeated Substring
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4808366.html