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.

题目链接:http://poj.org/problem?id=2406

题目大意:给出一个字符串 问它最多由多少相同的字串组成 

      如  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]。

讲解KMP循环节非常不错的博主  不懂得可以点进去。

代码:

#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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值