Sweety

Practice makes perfect

导航

Power Strings

Posted on 2015-02-14 08:49  蓝空  阅读(127)  评论(0编辑  收藏  举报

题目来源:http://poj.org/problem?id=2406


应该是最简单的KMP的应用了,并且也是next数组最简单的应用了

开始做题的时候感觉是用到了next数组,但是确实没有想到这个性质,虽然代码很简单但是一下想到这些确实还是不简单,这里一定注意next数组的性质


#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

const int maxm = 1000010;     // 模式串的最大长度
char str[maxm];
int  len, next[maxm];

void getNext(){
		int i = 0, j = next[0] = -1;
		while(i < len)	{
			if (j == -1 || str[i] == str[j]){
				++i; ++j;
				next[i] = j;
			}
			else
            j = next[j];
		}
/*			cout<<' ';
	for(int i=0;i<len;i++)
	cout<<str[i]<<" ";
	cout<<endl;
	for(int i=0;i<=len;i++)
	cout<<next[i]<<' ';
	cout<<endl;
*/
}
int main(){
	   while(~scanf("%s",str)&&str[0]!='.') {
	       len=strlen(str);
	       getNext();
	       int sum=1;
	       if(len%(len-next[len])==0)
	          sum=len/(len-next[len]);
	       cout<<sum<<endl;
	   }
}

next数组性质配套图片: