HDU 2406 Power Strings KMP 基础

来源:互联网 发布:编程男士性格好怪 编辑:程序博客网 时间:2024/04/28 00:02
Power Strings
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 43073 Accepted: 17980

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

14

3

题意:给出一个字符串 问该字符串最多可以有多少个相同的字串连接而成。

使用KMP算法,由于KMP的特殊性,答案可由标记数组直接的出,即sum=len/(len-1-p[len-1](前提是除的尽 否则答案为1)。

#include<stdio.h>#include<algorithm>#include<string.h>using namespace std;int p[1000005],len;char b[1000005];void find();int main(){int n,i,j,k,sum;while(scanf("%s",b)){if(b[0]=='.')break;find();len=strlen(b);if(len%(len-1-p[len-1])==0)printf("%d\n",len/(len-1-p[len-1]));elseprintf("1\n");}}void find(){int i,j=-1;p[0]=-1;for(i=1;b[i]!='\0';i++){if(j>=0 && b[j+1]!=b[i])j=p[j];if(b[j+1]==b[i])j++;p[i]=j;}}


0 0
原创粉丝点击