您的位置:首页 > 其它

Power Strings(poj2406 ,简单KMP)

2013-08-14 20:30 225 查看
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;
}
else
j=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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: