POJ-2406 Power Strings (KMP)

题意:给你一个字符串 求他的循环节长度

思路:利用 结论:len%(len - next[len]); 当next[len] == 0 则循环节为 1

完整代码:


#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e6+10;
int nex[maxn] ;
int len;
char s[maxn];
void getnext(){
	int i,j;
	i = 0,j = -1;
	nex[i] = j;
	while(i<len){
		
		if(j==-1||s[i]==s[j])
			nex[++i] = ++j;
		else  j = nex[j];
	}
}

int main(){
	while(scanf("%s",&s)){
		if(s[0]=='.') break;
		len = strlen(s); 
		getnext();
		if(len%(len-nex[len])==0) 
		printf("%d
",len/(len-nex[len]));
		else printf("1
"); 
	}
	return 0;
} 
 
原文地址:https://www.cnblogs.com/Tianwell/p/11211967.html