Categories: 数据结构和算法
Comments: No Comments
Published on: 2011 年 05 月 19 日

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as AK ,that is A concatenated K times, for some string A. Of course, we also want to know the period K.

#include <cstring>
using namespace std;
#define maxlen 1000002
int P[maxlen];
char str[maxlen];
int main(){
	int n = 1,len;//测试数据组数计数器
	while(scanf("%d",&len)!=EOF && len!=0){
		P[1] = 0;//P[]下标从1开始
		int j = 0;
		for (int i=2;i<=len;i++){
			while( j>0 && str[j]!=str[i-1] )
				j = P[j];
			if ( str[j] == str[i-1] )
			P[i] = j;
		printf("Test case #%d\n",n++);
		for (int k=2;k<=len;k++)
			if ( k%(k-P[k])==0 && k/(k-P[k])!=1)
					printf("%d %d\n",k,k/(k-P[k]));


No Comments - Leave a comment

Leave a comment

电子邮件地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Welcome , today is 星期五, 2018 年 03 月 23 日