poj-2406 Power Strings

绝地灬酷狼 2021-11-01 04:26 324阅读 0赞













Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 65854   Accepted: 27197

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.

思路:next[i]表示以第i个字符结束的最大后缀和最大前缀相等。n-next[n]则为最小的循环节。若n%(n-next[n])==0,那么n/(n-next[n])则为循环节出现的最大次数。

  1. #include <iostream>
  2. #include<string.h>
  3. using namespace std;
  4. const int maxn = 1e6+10;
  5. char a[maxn];
  6. int ne[maxn];
  7. int main()
  8. {
  9. while(scanf("%s",a+1)&&a[1]!='.')
  10. {
  11. memset(ne,0,sizeof(ne));
  12. int len = strlen(a+1);
  13. for(int i=2,j=0;i<=len;i++)
  14. {
  15. while(j&&a[i]!=a[j+1]) j=ne[j];
  16. if(a[i]==a[j+1]) j++;
  17. ne[i]=j;
  18. }
  19. if(len%(len-ne[len])==0) printf("%d\n",len/(len-ne[len]));
  20. else
  21. printf("1\n");
  22. }
  23. return 0;
  24. }

转载于:https://www.cnblogs.com/wjc2021/p/11300065.html

发表评论

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

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

相关阅读