标签:mem next bsp scanf clu can gre main 字符串
题意:输入一个字符串,问长度大于2的所有从首元素开始的子串是否为循环串,是的话循环了几次。
题解:用Kmp算法求出每个i的next【i】,并设t=i-next【i】,if(i%t==0&&i/t>1)。则该子串为循环串并且循环次数为i/t。
代码:
#include <string.h>
#include <iostream>
#include <stdio.h>
char str[1000005];
int next[1000005];
void getnext()
{
int i = 0,j = -1;
memset(next,0,sizeof(next));
next[0] = -1;
while (str[i])
{
if(j == -1 || str[i] == str[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
int main()
{
int n,cnt = 1;
while(scanf("%d",&n)!=EOF && n)
{
scanf("%s",str);
printf("Test case #%d\n",cnt++);
getnext();
int i,t;
for(i = 2;str[i-1];i++)
{
t = i-next[i];
if(i%t == 0 && i/t>1)
printf("%d %d\n",i,i/t);
}
puts("");
}
return 0;
}
标签:mem next bsp scanf clu can gre main 字符串
原文地址:http://www.cnblogs.com/LMissher/p/7403957.html