HDU 1358 Period(KMP+next数组的运用)

刺骨的言语ヽ痛彻心扉 2022-06-10 13:52 270阅读 0赞

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as A K , that is A concatenated K times, for some string A. Of course, we also want to know the period K.

Input

The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S. The second line contains the string S. The input file ends with a line, having the number zero on it.

Output

For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.

Sample Input

  1. 3
  2. aaa
  3. 12
  4. aabaabaabaab
  5. 0

Sample Output

  1. Test case #1
  2. 2 2
  3. 3 3
  4. Test case #2
  5. 2 2
  6. 6 2
  7. 9 3
  8. 12 4

题解:

给你一个串,从第二位起到最后的每一个i,问你从串的第一位到第i位是否能形成一个循环节,如果可以,输出当前的i和可以找到最多循环节的循环的次数

思路:

直接KMP搞一搞就好了,i-next[i]就相当于当前最小的循环节长度,设为t,当t%i==0&&t/i>1的时候即就是能形成循环的时候,因为KMP求出的就是最多的循环次数,输出t/i就是了

代码:

  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,j;
  25. i=0,j=-1;
  26. Next[0]=-1;
  27. while(T[i])
  28. {
  29. if(j==-1||T[i]==T[j])
  30. {
  31. i++;
  32. j++;
  33. Next[i]=j;
  34. }
  35. else
  36. j=Next[j];
  37. }
  38. }
  39. int main()
  40. {
  41. int i,j,n,cas=1;
  42. while(scanf("%d",&n)!=EOF&&n)
  43. {
  44. scanf("%s",T);
  45. init();
  46. printf("Test case #%d\n",cas);
  47. cas++;
  48. for(i=1;i<=n;i++)
  49. {
  50. int t=i-Next[i];
  51. if(i%t==0&&i/t>1)
  52. {
  53. printf("%d %d\n",i,i/t);
  54. }
  55. }
  56. printf("\n");
  57. }
  58. return 0;
  59. }

发表评论

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

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

相关阅读

    相关 运用

    一种数据类型(引用类型) 1、动态初始化:数据类型\[\] 数组名=new 数据类型\[大小\];int\[\] a=new int\[10\]; 数组的引用:数组名\[下

    相关 HDU 1358(kmp)

    题意:给出一个数字n,接下来一行是一个字符串,n是这个字符串的长度。求这个字符串的所有是循环字符串的前缀。 kmp中的next数组只得是第i个字符匹配错误,向前跳的位置nex