题意:在给定的字符串前i位找出循环节断的个数。
思路:还是kmp算法的应用变形,从给出字符串的第2位开始遍历,找出每次的匹配的字符串(length),前i为字符串长度为i,所以i/length就是循环节断的个数,要保证i/length能够整除,所以i%length==0。
移动位数(length) = 已匹配的字符数(i) - 对应部分匹配值(next[i])
【参考代码】
#include<cstdio>
#include<cstring>
using namespace std;
const int Max=1000001;
char str[Max];
int next[Max];
void getnext(int n)
{
int i=0,j=-1;
next[i]=-1;
while(i<n) {
if(j==-1||str[i]==str[j]) {
next[++i]=++j;
}
else j=next[j];
}
}
int main()
{
int len,cas=0;
while(scanf("%d",&len)&&len) {
scanf("%s",str);
getnext(len);
printf("Test case #%d\n",++cas);
for(int i=1;i<=len;i++) {
int length=i-next[i];
if(i!=length&&i%length==0)
printf("%d %d\n",i,i/length);
}
printf("\n");
}
return 0;
}