POJ 2406 Power Strings

来源:互联网 发布:轩辕世界神兽数据 编辑:程序博客网 时间:2024/05/01 22:51

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

abcdaaaaababab.

Sample Output

143
 
 
分析:此题主要考察字符串模式匹配算法即KMP算法;
代码:

#include <iostream>#include <cstring>#include <algorithm>using namespace std; char s[1000000];int len,next[1000000];void get_next(){     int i,j;     i=1; next[1]=0; j=0;     while(i<len)     {          if(j==0||s[i]==s[j])          {              ++i;              ++j;              next[i]=j;          }          else  j=next[j];     }}

int main(){    int k;    while(cin>>s)    {              if(s[0]=='.') break;        len=strlen(s);        get_next();        if(len%(len-next[len])==0)        {   k=len/(len-next[len]);   cout<<k<<endl;  }  else cout<<1<<endl;          }    return 0;}

原创粉丝点击