HDU1358:Period

第一次做KMP。还没有理解透。

在自己写一遍时没有让next[0]初始化为-1。

还有就是next应该是c++中的关键字,提交后编译错误。

From:

http://blog.csdn.net/libin56842/article/details/8498391

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include "ctype.h"
#include "cstdlib"
#include<cmath>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <vector>
using namespace std;
	
char c[1000000];
int ne[1000000];


void cal(){
	int i=0,j=-1;
	ne[0]=-1;
	while(c[i]){
		if(c[i]==c[j]||j==-1){
			++i;
			++j;
			ne[i]=j;
		}
		else{
			j=ne[j];
		}
	}
}
void kmp(){
	for(int i=2;c[i-1];++i)
	{
		int t=i-ne[i];
		if(i%t==0 && i/t>1){
			printf("%d %d\n",i,i/t);
		}
	}
}
int main()
{
	int i,j,k,n,m,a,b,l;
	k=1;
	while(cin>>b,b){
		scanf("%s",c);
		printf("Test case #%d\n",k++);
		cal();
		kmp();
		printf("\n");
	}	
	
	 return 0;
}


 

posted @ 2015-04-28 16:30  Traveller_Leon  阅读(137)  评论(0)    收藏  举报