1. 程式人生 > >【POJ 2406】Power Strings

【POJ 2406】Power Strings

【題目】

傳送門

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

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

【分析】

大致意思:一個字串由它的一個子串不斷拼接而成,求最長拼接的長度

比如說樣例,ababab 就是由 ab 拼接 3 次形成的,最長的長度也就是 3

很容易想到用 KMP 中的 next 陣列求最小迴圈節,答案是 l/(l-next[l])

有一個要注意的地方是當 l\; mod\; (l-next[l])\neq 0 時,如 abababa,答案也只能為 1

【程式碼】

#include<cstdio>
#include<cstring>
#include<algorithm>
#define L 1000005
using namespace std;
char s[L];
int next[L];
int main()
{
	int i,j,l,ans;
	scanf("%s",s+1);
	while(s[1]!='.')
	{
		l=strlen(s+1);
                j=0,next[1]=0;
		for(i=2;i<=l;++i)
		{
			while(j&&s[i]!=s[j+1])  j=next[j];
			if(s[i]==s[j+1])  ++j;
			next[i]=j;
		}
		ans=1;
		if(l%(l-next[l])==0)
		    ans=l/(l-next[l]);
		printf("%d\n",ans);
		scanf("%s",s+1);
	}
	return 0;
}