poj2406 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.

先对原串进行kmp匹配,考虑一个答案,设第一个重复的子串为1..i。那么对于点p=i+1,需要满足如下条件。
1:子串长度必须是原串的因数,即l%(p-1)==0。
2:后面必须是这个串的重复,即next[p]==1&&next[l]==l-p+1。
最后判断一下无解的情况。
还有一种更简单的方法,写在bzoj1355【见这里】

#include
#include
char s[1000010];
int next[1000010];
int main()
{
    int i,j,k,m,n,p,q,x,y,z,l;
    bool flag;
    while (scanf("%s",s+1)&&(strlen(s+1)!=1||s[1]!='.'))
    {
        l=strlen(s+1);
        for (i=2,j=0;i<=l;i++)
        {
            while (j&&s[i]!=s[j+1]) j=next[j];
            if (s[i]==s[j+1]) j++;
            next[i]=j;
        }
        flag=0;
        for (i=1;i<=l;i++)
          if (next[i]==1&&l%(i-1)==0&&next[l]==l-i+1)
          {
            flag=1;
            printf("%d\n",l/(i-1));
            break;
          }
        if (!flag) printf("1\n");
    }
}

你可能感兴趣的:(字符串,poj)