POJ 2406-Power Strings(重複子串-KMP中的next陣列)

kewlgrl發表於2017-04-11
Power Strings
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 47642   Accepted: 19867

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


題目意思:

一個字串由K個迴圈節組成,求迴圈節最小的時候其字元的個數L。

解題思路:

暴力又又TLE了,然後,發現要利用next陣列的特性:模式串長度為n,其第1位到next[n]與模式串第n-next[n]位到n位是匹配的。

根據定義,next[i]表示模式串0~i-1長度中,字尾與字首的最長匹配子串的長度,所以next[n]表示整個模式串字尾與字首的最長匹配子串的長度,

next[KL] = (K-1)L,即next[n] = n - L,所以L = n-next[n],所以n-next[n]表示一個最小迴圈節的長度。

題解參考



#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<map>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define INF 0xfffffff
#define MAXN 1000010
char t[MAXN];
int next[MAXN];
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("G:/cbx/read.txt","r",stdin);
    //freopen("G:/cbx/out.txt","w",stdout);
#endif
    ios::sync_with_stdio(false);
    cin.tie(0);
    while(cin>>t)
    {
        if(t[0]=='.') break;
        memset(next,0,sizeof(next));
        int len=strlen(t);
        int ans=1;
        int p=0,cur;
        next[0]=-1;
        next[1]=0;
        for(cur=2; cur<=len; ++cur)//求next陣列
        {
            while(p>=0&&t[p]!=t[cur-1])
                p=next[p];
            next[cur]=++p;
        }
        if(len%(len-next[len])==0)//模式串第1位到next[n]與模式串第n-next[n]位到n位是匹配的
            ans=len/(len-next[len]);
        cout<<ans<<endl;
    }
    return 0;
}


相關文章