zoj 2177 Period (KMP )

和上一题一样-,-

#include<stdio.h>
#include<string.h>
char str[1000005];
int P[1000005];
int next[1000005];
void get_next(){
    int i = 0, j = -1;
    next[0] = -1;
	int len=strlen(str);
    while(i < len){
        if(j == -1 || str[i] == str[j]){
            i ++; j ++;
            next[i] = j;
        }
        else j = next[j];
    }
}
void initP()
{
	P[0]=0;
	P[1]=0;
	int i,j=0;
	int len=strlen(str);
	for(i=2;i<=len;i++)
	{
		while(j>0&&str[j]!=str[i-1])
			j=P[j];
		if(str[j]==str[i-1])
			j++;
		P[i]=j;
	}
}
int main()
{
	int Case=1;
	int N,i;
	while(scanf("%d",&N))
	{
		if(N==0) break;
		scanf("%s",str);
		initP();
		//get_next();
		int len=strlen(str);
		printf("Test case #%d\n",Case++);
		for(i=2;i<=len;i++)
		{
			if(i%(i-P[i])==0)
			{
				if(i/(i-P[i])==1) continue;
				printf("%d %d\n",i,i/(i-P[i]));
			}
		}



		printf("\n");
	}
	return 0;
}


你可能感兴趣的:(zoj 2177 Period (KMP ))