【POJ2406】 Power Strings (KMP)
Power StringsDescription
Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.Output
For each s you should print the largest n such that s = a^n for some string a.Sample Input
abcd aaaa ababab .Sample Output
1 4 3Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.
【题意】
一个字符串的最大重复字串。
即一个字符串是一个子串最多重复多少次得到的。
【分析】
① len==1||s[next[len-1]]!=s[len-1] ans=1;
② len%(len-next[len])==0 ans= len/(len-next[len]);
原因如图:
代码如下:
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 #include<queue> 7 using namespace std; 8 #define Maxn 1000010 9 10 char s[Maxn]; 11 int len,nt[Maxn]; 12 13 14 void kmp() 15 { 16 nt[1]=0; 17 int p=0; 18 for(int i=2;i<=len;i++) 19 { 20 while(s[i]!=s[p+1]&&p) p=nt[p]; 21 if(s[i]==s[p+1]) p++; 22 nt[i]=p; 23 } 24 } 25 26 int main() 27 { 28 int n,i; 29 while(1) 30 { 31 gets(s+1); 32 len=strlen(s+1); 33 if(len==1&&s[1]=='.') break; 34 kmp(); 35 if(len%(len-nt[len])==0) printf("%d\n",len/(len-nt[len])); 36 else printf("1\n"); 37 } 38 }
2016-07-20 16:30:02