题目链接:http://poj.org/problem?id=2406
Time Limit: 3000MS Memory Limit: 65536K
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
题意:
求给出字符串,最多是多少个循环节组成的。
题解:
利用len % (len-Next[len]) == 0的话,len-Next[len]是最小循环节长度的性质。
AC代码:
#include<cstdio>
#include<cstring>
using namespace std; const int MAXpat = +; char pat[MAXpat];
int Next[MAXpat],len; void getNext()
{
int i=, j=-;
len=strlen(pat);
Next[]=-;
while(i<len)
{
if(j == - || pat[i] == pat[j]) Next[++i]=++j;
else j=Next[j];
//printf("now i=%d j=%d next[%d]=%d pat[%d]=%c\n",i,j,i,Next[i],i,pat[i]);
}
}
int main()
{
while(scanf("%s",pat))
{
if(pat[]=='.' && pat[]=='\0') break;
getNext();
if(len%(len-Next[len])==) printf("%d\n",len/(len-Next[len]));
else printf("1\n");
}
}
注意:
①当且仅当len%(len-Next[len])==0时,len-Next[len]才是最小循环节长度。
②关于Next数组,我觉得这个图很不错的展示了Next数组存储了啥: