POJ 2406 Power Strings【KMP判字符串循环节】

由KMP求出 f a i l [ ] fail[] fail[]

设当前串长度为 l e n len len

( l e n − f a i l [ l e n ] )    ∣    l e n (len-fail[len])\ \ |\ \ len (lenfail[len])    len

则循环节长度为 l e n l e n − f a i l [ l e n ] \frac{len}{len-fail[len]} lenfail[len]len

否则无循环节。

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define db double
#define sg string
#define ll long long
#define rel(i,x,y) for(ll i=(x);i<(y);i++)
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define red(i,x,y) for(ll i=(x);i>=(y);i--)
#define res(i,x) for(ll i=head[x];i;i=nxt[i])
using namespace std;

const ll N=1e6+5;
const ll Inf=1e18;
const db Eps=1e-10;

char ch[N];
ll len,fail[N];

void kmp() {
	len=strlen(ch+1);
	fail[1]=0;ll j=0;
	rep(i,2,len) {
		while(j>0&&ch[i]!=ch[j+1]) j=fail[j];
		if(ch[i]==ch[j+1]) j++;fail[i]=j;
	}
}

int main() {
	while(~scanf("%s",ch+1)) {
		if(ch[1]=='.') return 0;
		
		kmp();
		
		ll ret=1;
		
		if(len%(len-fail[len])==0) {
			printf("%lld\n",len/(len-fail[len]));
		} else printf("%lld\n",ret);
	}

	return 0;
}
    原文作者:KMP算法
    原文地址: https://blog.csdn.net/yanzhenhuai/article/details/83382148
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞