Power Strings(poj2406 ,简单KMP)

来源:互联网 发布:期货数据库 编辑:程序博客网 时间:2024/06/05 10:19

http://poj.org/problem?id=2406

http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?cid=5412&pid=1008&ojid=1

Power Strings

Time Limit : 6000/3000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)

Total Submission(s) : 0   Accepted Submission(s) : 0

Problem 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

 解析:

 题意:

 求字符串最大循环次数

 思路:

 定理

 if(len%(len-next[len])==0)ans=len/(len-next[len]);

 else ans=1;

Accepted 94 MS 5596 KB GNU C++

*/

#include<string.h>#include<stdio.h>#include<algorithm>#include <iostream>using namespace std;const int maxn =1000000+10;int next[maxn];char s[maxn];void get_next(){next[0]=-1;int j=-1;int i=0;while(s[i]!='\0'){if(j==-1||s[i]==s[j]){    i++;j++;next[i]=j;}elsej=next[j];}}int main(){int j,i;    while(scanf("%s",s)!=EOF&&s[0]!='.')    {    get_next();    int len=strlen(s);    //for(i=0;i<=len;i++)    //printf("next[%d]=%d\n",i,next[i]);    j=len-next[len];//循环节长度    if(len%j==0)    {    printf("%d\n",len/j);    }    else    printf("1\n");    }    return 0;}


原创粉丝点击