hdu 1358 KMP


http://acm.hdu.edu.cn/showproblem.php?pid=1358
長さnの文字列を与えて、その文字列の循環接頭辞の長さを求めて、循環回数;
例:ababababの最初の4文字、循環文字列はabで、2つの循環周期ab|abの最初の6文字があって、循環文字列はabで、3つの循環周期ab|ab|ab|abの前の8文字があって、循環文字列はabで、4つの循環周期ab|ab|ab|ab出力があります:4 2 6 3 8 4
#include<stdio.h>
#define SIZE 1000006
int next[SIZE];
char str[SIZE];

void getnext(int n)
{
	int i=0,j=-1;
	next[0]=-1;
	while(i<n){
		if(j==-1 || str[i]==str[j]){
			i++;
			j++;
			next[i] = j;
		}
		else{
			j = next[j];
		}
	}
}
int main()
{
	int nT=1,n,i,mixed,circulate;
	while(scanf("%d",&n),n){
		getchar();
		gets(str);
		getnext(n);
		printf("Test case #%d
",nT++); for(i=1;i<=n;i++){ mixed = 2*next[i]-i; // circulate = next[i]-mixed; // if(mixed>=0 && i%circulate==0){ printf("%d %d
",i,i/circulate); } } printf("
"); } return 0; }