POJ 2406-Power Strings(重复子串-KMP中的next数组)

Bertha 。 2022-06-17 00:17 310阅读 0赞

Power Strings














Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 47642   Accepted: 19867

Description

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

  1. abcd
  2. aaaa
  3. ababab
  4. .

Sample Output

  1. 1
  2. 4
  3. 3

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

Source

Waterloo local 2002.07.01

题目意思:

一个字符串由K个循环节组成,求循环节最小的时候其字符的个数L。

解题思路:

暴力又又TLE了,然后,发现要利用next数组的特性:模式串长度为n,其第1位到next[n]与模式串第n-next[n]位到n位是匹配的。

根据定义,next[i]表示模式串0~i-1长度中,后缀与前缀的最长匹配子串的长度,所以next[n]表示整个模式串后缀与前缀的最长匹配子串的长度,

next[KL] = (K-1)L,即next[n] = n - L,所以L = n-next[n],所以n-next[n]表示一个最小循环节的长度。

题解参考

20170411155843955

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<iomanip>
  4. #include<cmath>
  5. #include<cstdlib>
  6. #include<cstring>
  7. #include<map>
  8. #include<algorithm>
  9. #include<vector>
  10. #include<queue>
  11. using namespace std;
  12. #define INF 0xfffffff
  13. #define MAXN 1000010
  14. char t[MAXN];
  15. int next[MAXN];
  16. int main()
  17. {
  18. #ifdef ONLINE_JUDGE
  19. #else
  20. freopen("G:/cbx/read.txt","r",stdin);
  21. //freopen("G:/cbx/out.txt","w",stdout);
  22. #endif
  23. ios::sync_with_stdio(false);
  24. cin.tie(0);
  25. while(cin>>t)
  26. {
  27. if(t[0]=='.') break;
  28. memset(next,0,sizeof(next));
  29. int len=strlen(t);
  30. int ans=1;
  31. int p=0,cur;
  32. next[0]=-1;
  33. next[1]=0;
  34. for(cur=2; cur<=len; ++cur)//求next数组
  35. {
  36. while(p>=0&&t[p]!=t[cur-1])
  37. p=next[p];
  38. next[cur]=++p;
  39. }
  40. if(len%(len-next[len])==0)//模式串第1位到next[n]与模式串第n-next[n]位到n位是匹配的
  41. ans=len/(len-next[len]);
  42. cout<<ans<<endl;
  43. }
  44. return 0;
  45. }

发表评论

表情:
评论列表 (有 0 条评论,310人围观)

还没有评论,来说两句吧...

相关阅读