您的位置:首页 > 其它

HDU 1358(KMP思想求周期)

2018-01-25 11:12 169 查看
题意

                  给定一个长度为1e6的字符串 求出这个串中所有有循环节并且周期大于等于二的串  并且输出这些串的起点和周期

思路

  

                  既然是求周期问题 可以利用KMP算法中next数组来求解   由于len-next[len]就是当前点的最小循环节  所以 可以用取余的方式来判断是不是刚好形成周期串  自己在写这道题的时候算错了下标被坑了好久  心累~

代码

#include <cstring>
#include <cstdio>

const int N = 1e6 + 10;
const int M = 1e4 + 10;
char str
;
int next
, len;;

void Pre_Kmp()
{
int i , j ;
i = 0, j = next[0] = -1;
while (i < len) {
while (j != -1 && str[j] != str[i]) j = next[j];
next[++i] = ++j;
}
return ;
}
int main()
{
int Case = 1;
while (scanf("%d",&len) && len) {
scanf("%s",str);
printf("Test case #%d\n",Case ++);
Pre_Kmp();
for (int i = 1 ; i < len + 1; i ++) {
if (next[i] && i % (i - next[i]) == 0)
printf("%d %d\n",i , i / (i - next[i]));
}
puts("");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: