1. 程式人生 > >Power Strings(POJ-2406)(KMP簡單迴圈節)

Power Strings(POJ-2406)(KMP簡單迴圈節)

Power Strings
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 50983 Accepted: 21279

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.

題目大意:給出一個字串 問它最多由多少相同的字串組成 

      如  abababab由4個ab組成

題目分析:要用到KMP中的next陣列來計算最小迴圈節。

KMP最小迴圈節、迴圈週期:

定理:假設S的長度為len,則S存在最小迴圈節,迴圈節的長度L為len-next[len],子串為S[0…len-next[len]-1]。

(1)如果len可以被len - next[len]整除,則表明字串S可以完全由迴圈節迴圈組成,迴圈週期T=len/L。

(2)如果不能,說明還需要再新增幾個字母才能補全。需要補的個數是迴圈個數L-len%L=L-(len-L)%L=L-next[len]%L,L=len-next[len]。


程式碼:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int N=1000000+999;
char s2[N];
int nex[N];
void makeNext(int m)
{
    int i,j;
    nex[0] = 0;
    for (i = 1,j = 0; i < m; i++)
    {
        while(j > 0 && s2[i] != s2[j])
            j = nex[j-1];
        if (s2[i] == s2[j])
            j++;
        nex[i] = j;
    }
}
int main()
{
    int n;
    while(scanf(" %s",s2)!=EOF)
    {
        if(s2[0]=='.') break;
        n=strlen(s2);
        memset(nex,0,sizeof(nex));
        makeNext(n);
        int j=nex[n-1]; //1到n-1的最長字首字尾相等長度
        int ans=1;
        if(n%(n-j)==0) //判斷是否能由迴圈節組成
            ans=n/(n-j); //由幾個迴圈節構成
        printf("%d\n",ans);
    }
    return 0;
}