首页 > 代码库 > poj 2406 Power Strings

poj 2406 Power Strings

Power Strings
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 33636 Accepted: 13973

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

题目大意:给出一个字符串,求这个串是有几个子串构成的思路:用KMP算法中的next数组,这个字符串的next数组里边,字符串的总长度减去最后一个字符所对应的next值就是子串的长度 具体为什么,应该是next数组的值是根据这个字符串本身,用一定规则得出的,这个真的好巧妙的说,kmp算法,好好看看。2014,12,5

#include<stdio.h>
#include<string.h>
char x[1100000];
int next[1100000];
void getnext(char s[]){
	int len1,i,j;
	len1=strlen(s);
	i=0;j=-1;
	next[i]=j;
	while(i<len1){
		if(j==-1||s[i]==s[j]){
			++i;++j;
			next[i]=j;
		}
		else j=next[j];
	}
}
int main(){
	int t,len;
	while(scanf("%s",x)){
		getnext(x);
		if(x[0]=='.') break;
		else {
			len=strlen(x);
			t=len-next[len];
			if(len%t==0)
				printf("%d\n",len/t);
			else printf("1\n");	
		}
	}
	return 0;
}


poj 2406 Power Strings