POJ:2406-Power Strings(寻找字符串循环节)

Power Strings

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

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.


就是一个寻找字符串的循环节,用KMP的思想,其实很简单就是len/(len-next[n])。(当然是在没有余数的情况下,不然就是1)


#include
#include
#include
using namespace std;
const int maxn = 1e6+100;
char s[maxn];
int next[maxn];

void cal_next()
{
    int k;
    next[0] = k = -1;
    int len = strlen(s);
    for(int i=1;iwhile(k>-1 && s[i] != s[k+1])
            k = next[k];
        if(s[i] == s[k+1])
            k++;
        next[i] = k;
    }
}

int main()
{
    while(scanf("%s",s))
    {
        if(s[0] == '.' && s[1] == 0)
            break;
        cal_next();
        int len = strlen(s);
        if(len%(len - next[len-1] - 1) == 0)
            printf("%d\n",len/(len - next[len-1] - 1));
        else
            printf("1\n");
        memset(s,0,sizeof(s));
    }
    return 0;
}

你可能感兴趣的:(数据结构-KMP)