POJ-2406 Power string

Power string
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 54809 Accepted: 22806

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.

题解:

这是考察KMP算法中NEXT[]数组(就是寻找字符串S可以有最长子串循环得到);Next[i]表示到字符串S的第I个字符时形成的最长的前缀=后缀。如果len%(len-Next[len])==0,那么就是明其可以由子串循环组成,如果不为零,则只能由其本身一次组成

AC代码为:

#include<iostream>
#include<cstring>
#include<string>
using namespace std;
const int maxn=1e6+5;
char s[maxn];
int Next[maxn];


void GetNext()
{
int len = strlen(s);
Next[0]=Next[1]=0;
for(int i=1;i<len;i++)
{
int j=Next[i];
while(j && s[i]!=s[j]) j=Next[j];
Next[i+1]=s[i]==s[j]? j+1:0;
}
}


int main()
{
while(~scanf("%s",s) && s[0]!='.')
{
int len = strlen(s);
GetNext();
int num = len%(len-Next[len])==0? len/(len-Next[len]):1;
cout<<num<<endl;
}
return 0;



posted @ 2018-03-29 23:17  StarHai  阅读(264)  评论(0编辑  收藏  举报