【kmp算法next数组-串的最小循环节/循环周期】Period HDU - 1358

迈不过友情╰ 2022-06-07 02:22 291阅读 0赞

Think:
1知识点:通过kmp算法的next数组求解串的最小循环节和循环周期
2题意:一个长为N (2 <= N <= 1 000 000) 的字符串,询问前缀串长度为k(k > 1)的串是否是一个周期串,即k = A…A;若是则按k从小到大的顺序输出k和周期数
3解题知识点:
(1):一个串的最小循环节长度:len - next[len]
(2):若len%(len-next[len]) == 0, 则这个字符串的最小周期为len/(len-next[len])

vjudge题目链接

建议参考博客—参考博主题意

以下为Presentation Error代码—题目要求每组测试数据之后需要输出空行

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <algorithm>
  4. using namespace std;
  5. const int size_P = 1000414;
  6. int _next[size_P];
  7. char st1[size_P];
  8. void get_next(char *P, int len_P);
  9. int main(){
  10. int k = 1;
  11. int n, i, cir_len;
  12. while(~scanf("%d", &n) && n){
  13. scanf("%s", st1);
  14. get_next(st1, n);
  15. printf("Test case #%d\n", k++);
  16. for(i = 1; i <= n; i++){
  17. cir_len = i - _next[i-1];
  18. if(cir_len != i && i%cir_len == 0)
  19. printf("%d %d\n", i, i/cir_len);
  20. }
  21. }
  22. return 0;
  23. }
  24. void get_next(char *P, int len_P){
  25. int q, k;
  26. _next[0] = 0;
  27. k = 0;
  28. for(q = 1; q < len_P; q++){
  29. while(k > 0 && P[k] != P[q]){
  30. k = _next[k-1];
  31. }
  32. if(P[k] == P[q])
  33. k++;
  34. _next[q] = k;
  35. }
  36. }

以下为Accepted代码

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <algorithm>
  4. using namespace std;
  5. const int size_P = 1000414;
  6. int _next[size_P];
  7. char st1[size_P];
  8. void get_next(char *P, int len_P);
  9. int main(){
  10. int k = 1;
  11. int n, i, cir_len;
  12. while(~scanf("%d", &n) && n){
  13. scanf("%s", st1);
  14. get_next(st1, n);
  15. printf("Test case #%d\n", k++);
  16. for(i = 1; i <= n; i++){
  17. cir_len = i - _next[i-1];
  18. if(cir_len != i && i%cir_len == 0)
  19. printf("%d %d\n", i, i/cir_len);
  20. }
  21. printf("\n");
  22. }
  23. return 0;
  24. }
  25. void get_next(char *P, int len_P){
  26. int q, k;
  27. _next[0] = 0;
  28. k = 0;
  29. for(q = 1; q < len_P; q++){
  30. while(k > 0 && P[k] != P[q]){
  31. k = _next[k-1];
  32. }
  33. if(P[k] == P[q])
  34. k++;
  35. _next[q] = k;
  36. }
  37. }

发表评论

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

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

相关阅读