首页 > 代码库 > poj2406 kmp

poj2406 kmp

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的next数组求最小环,有一点必须注意,整个字符串必须都是循环构成的,否则就输出1
技术分享
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define ll long long
#define mod 1000000007
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1

using namespace std;

const double g=10.0,eps=1e-9;
const int N=1000000+5,maxn=1000000+5,inf=0x3f3f3f3f;

int Next[N],slen;
string str;

void getnext()
{
    int k=-1;
    Next[0]=-1;
    for(int i=1;i<slen;i++)
    {
        while(k>-1&&str[k+1]!=str[i])k=Next[k];
        if(str[k+1]==str[i])k++;
        Next[i]=k;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
 //   cout<<setiosflags(ios::fixed)<<setprecision(2);
    while(cin>>str){
        if(str==".")break;
        slen=str.size();
        getnext();
        int ans=slen-Next[slen-1]-1;
        if(slen%ans)cout<<1<<endl;
        else cout<<slen/ans<<endl;
    }
    return 0;
}
View Code

 

poj2406 kmp