POJ 2406 KMP 解题报告

来源:互联网 发布:淘宝不能发布宝贝2手 编辑:程序博客网 时间:2024/06/05 18:43

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.

代码如下:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define N 1000010 char p[N];  int m,nxt[N];void getnext()  {      int i=0,j=nxt[0]=-1;      while(i<m)      {          if(j==-1||p[i]==p[j])          {              ++i;++j;              nxt[i]=p[i]!=p[j]?j:nxt[j];          }          else j=nxt[j];      }  }    int main()  {     while(scanf("%s",p)!=EOF)      {          if(p[0]=='.') break;          m=strlen(p);          getnext();          int ans=1;          if(!(m%(m-nxt[m]))) ans=m/(m-nxt[m]);          printf("%d\n",ans);      }      return 0;} 
原创粉丝点击