Power Strings

布满荆棘的人生 2022-12-21 06:29 219阅读 0赞

Power Strings

Description
Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “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
.
Output
1
4
3
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. char a[100010000];//本题测试数据很多,数组记得开大点
  5. int next[10001000];
  6. void getnext(int len)
  7. {
  8. int i=0,j=-1;
  9. next[0]=-1;
  10. while(i<len)
  11. {
  12. if(j==-1||a[j]==a[i])
  13. {
  14. j++;
  15. i++;
  16. next[i]=j;
  17. }
  18. else
  19. j=-1;
  20. }
  21. }
  22. int main()
  23. {
  24. while(~scanf("%s",a))
  25. {
  26. if(a[0]=='.')
  27. break;
  28. else
  29. {
  30. int len=strlen(a);
  31. memset(next,0,sizeof(next));
  32. getnext(len);
  33. int n=len-next[len];
  34. if(n!=len&&len%n==0)
  35. printf("%d\n",len/n);
  36. else
  37. printf("1\n");
  38. }
  39. }
  40. }

利用KMP算法,求字符串的特征向量next,若len可以被len - next[len]整除,则最大循环次数n为len/(len - next[len]),否则为1。

发表评论

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

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

相关阅读

    相关 Power Strings

    写在题目前:POJ太好用啦! 描述 给定两个字符串a和b,我们将\ b定义为它们的串联。例如,如果a =“abc”而b =“def”则a \ b =“abcdef”。如果我