POJ 2406 Power Strings(KMP+最小循环节)

电玩女神 2022-06-10 14:08 295阅读 0赞

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.

题解:

给一个串,问是由最多几个循环节组成的,直接用最小循环节长度len-next[len]判断一下就好了,如果能整除len就输出len/最小循环节长度,否则输出1

代码:

  1. #include<algorithm>
  2. #include<iostream>
  3. #include<cstring>
  4. #include<stdio.h>
  5. #include<math.h>
  6. #include<string>
  7. #include<stdio.h>
  8. #include<queue>
  9. #include<stack>
  10. #include<map>
  11. #include<vector>
  12. #include<deque>
  13. using namespace std;
  14. #define lson k*2
  15. #define rson k*2+1
  16. #define M (t[k].l+t[k].r)/2
  17. #define INF 1008611111
  18. #define ll long long
  19. #define eps 1e-15
  20. int Next[1000005];
  21. char T[1000005];
  22. void init()
  23. {
  24. int i=0,j=-1;
  25. Next[0]=-1;
  26. while(T[i])
  27. {
  28. if(j==-1||T[i]==T[j])
  29. {
  30. i++;
  31. j++;
  32. Next[i]=j;
  33. }
  34. else
  35. j=Next[j];
  36. }
  37. }
  38. int main()
  39. {
  40. int i,j,n,len;
  41. while(gets(T)!=NULL)
  42. {
  43. if(T[0]=='.')
  44. break;
  45. init();
  46. len=strlen(T);
  47. n=len-Next[len];
  48. if(len%n==0)
  49. printf("%d\n",len/n);
  50. else
  51. printf("1\n");
  52. }
  53. return 0;
  54. }

发表评论

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

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

相关阅读