码迷,mamicode.com
首页 > 其他好文 > 详细

E - Power Strings

时间:2020-03-31 14:21:25      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:string   type   time   cee   long   math   put   完全   repr   

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。就是前6个和后6个相同。设T【8】为S的后6位+S最后2位,因为S【8】为S的前6位+S最后2位,所以T==S。相当于把S向后移动2位得到T。可以看出S[3]~S[8]和T[1]~T[6]是一样的,可得T[5]~T[6]==S[7]~S[8]。同样因为S和T最后2位相同,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;
}

 

E - Power Strings

标签:string   type   time   cee   long   math   put   完全   repr   

原文地址:https://www.cnblogs.com/studyshare777/p/12604467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!