poj2406之kmp应用

Power Strings
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 26792   Accepted: 11211

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

关于周期=len-next[len]:


但是要注意球到周期后这整个字符串不一定由周期构成,如上图2~3多余出来的(aaaabbaa可以求道最小周期是aaaabb),这里所谓求到的周期是把这个周期循环下去能包含所给的字符串,所以还要判断len%(len-next[len]) == 0


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#define INF 99999999
using namespace std;

const int MAX=1000000+10;
char s[MAX];
int next[MAX];

int get_next(char *a){
	int i=-1,j=0,len=strlen(a);
	next[0]=-1;
	while(j<len){
		if(i == -1 || a[i] == a[j])next[++j]=++i;
		else i=next[i];
	}
	if(len%(len-next[len]) == 0)return len/(len-next[len]);
	return 1;
}

int main(){
	while(cin>>s,s[0] != '.'){
		cout<<get_next(s)<<endl;
	}
	return 0;
}


你可能感兴趣的:(poj2406之kmp应用)