E - Power Strings

E - Power Strings

Given two strings a and b we define ab to be their concatenation. For example, if a = "abc" and b = "def" then ab = "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.

题目描述:

求一个字符串能分成最多多少个相同子串。(完全分割成相同的n份,求n)

分析:

根据kmp算法的next的性质。next[strlen-1]+1就是整个字符串最大前后缀相同的长度。要计算周期,设d=strlen-(next[strlen-1]+1),那么周期T=strlen/d(如果strlen%d==0),否则就不能分。

证明如下:

假设字符串为s【8】,整个字符串最大前后缀相同的长度next[strlen-1]+1是6,d就是8-6=2。把它向后移动2位,记为T【8】。可以看出S[3]~S[8]和T[1]~T[6]是一样的,可得T[5]~T[6]==S[7]~S[8]。因为前缀6位和后缀6位相同,所以T[7]~T[8]==S[7]~S[8]==T[5]~T[6]。以此类推,s一定可以分成strlen/d份相同的子串。如果strlen%d!=0,就说明有多余的,不能分割。

代码:

 

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<sstream>
#include<vector>
#include<stack>
#include<deque>
#include<cmath>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=1e6+6;
int neet[maxn];
void getnext(string ptr,int len)
{
    neet[0]=-1;
    int k=-1;
    for(int i=1;i<len;i++)
    {
        while(k>-1&&ptr[k+1]!=ptr[i]) k=neet[k];
        if(ptr[k+1]==ptr[i]) k++;
        neet[i]=k;
    }
}
int main()
{    
    while(1)
    {
        char s[maxn];
        scanf("%s",&s);
        if(s[0]=='.'&&strlen(s)==1) break;
        int n=strlen(s);
        getnext(s,n);
        int d=n-(neet[n-1]+1);
        if(n%d==0) printf("%d\n",n/d);
        else printf("1\n");
    }         
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/studyshare777/p/12604467.html