【POJ 2406】Power Strings KMP求最小循环节

                                          Power Strings

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 57937   Accepted: 24066

Description

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).

Input

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.

Output

For each s you should print the largest n such that s = a^n for some string a.

Sample Input

abcd
aaaa
ababab
.

Sample Output

1
4
3

题意:求该字符串的最小循环节,并输出该字符串是由几个最小循环节组成的。

例如: ababab ,最小循环节是ab,一共有三个;

            ababa ,不满足循环结构,输出1;

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int nexts[1000005];
char s[1000005];
void kmp(char *s,int *nexts,int len) 
{
	nexts[0]=-1;
	int k=-1;
	for(int q=1; q<len; q++) 
	{
		while(k>-1&&s[k+1]!=s[q])
			k=nexts[k];
		if(s[k+1]==s[q])
			k++;
		nexts[q]=k;
	}
}
int main() 
{
	int n,len;
	std::ios::sync_with_stdio(false);
	while(cin>>s&&s[0]!='.') 
	{
		len=strlen(s);
		kmp(s,nexts,len);
		n=len-nexts[len-1]-1;
		if(len%n==0)
		cout<<len/n<<endl;
		else
		cout<<1<<endl;
	}
	return 0;
}

KMP算法next数组,next[len-1]表示该字符串的最大前缀与最大后缀相同时的位数,下标从0开始。

详细使用方法:超详细理解:kmp算法next数组求解过程和回溯的含义

猜你喜欢

转载自blog.csdn.net/Xylon_/article/details/81633507