1. 程式人生 > >poj 2406 Power Strings(KMP求迴圈次數)

poj 2406 Power Strings(KMP求迴圈次數)

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.

Source


題意:

求最小子串的迴圈次數;

思路:(轉)

KMP,next[]表示模式串如果第i位(設str[0]為第0位)與文字串第j位不匹配則要回到第next[i]位繼續與文字串第j位匹配。則模式串第1位到next[n]與模式串第n-next[n]位到n位是匹配的。所以思路和上面一樣,如果n%(n-next[n])==0,則存在重複連續子串,長度為n-next[n]。

例如:a    b    a    b    a    b

next:-1   0    0    1    2    3    4

next[n]==4,代表著,字首abab與字尾abab相等的最長長度,這說明,ab這兩個字母為一個迴圈節,長度=n-next[n];


程式碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define MAXN 1000017
int next[MAXN];
int len;
void getnext( char T[])
{
    int i = 0, j = -1;
    next[0] = -1;
    while(i < len)
    {
        if(j == -1 || T[i] == T[j])
        {
            i++,j++;
            next[i] = j;
        }
        else
            j = next[j];
    }
}

int main()
{
    char ss[MAXN];
    int length;
    while(~scanf("%s",ss))
    {
        if(ss[0] == '.')
            break;
        len = strlen(ss);
        getnext(ss);
        length = len - next[len];
        if(len%length == 0)
            printf("%d\n",len/length);
        else
            printf("1\n");
    }
    return 0;
}