Power Strings KMP next数组的应用

题目:

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).

输入:

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.

输出:

For each s you should print the largest n such that s = a^n for some string a.

样例输入:

abcd
aaaa
ababab
.

样例输出:

1
4
3

题意:

给出一串字符串长度为len,求一个最小长度为A的循环体,有一个K满足K*A=len,求这个K的最大值,也就是求这个循环体长度的最小值。这个题用了next数组的应用。

有一个定理,如果一个字符串的长度为len,当且仅当len%(len-net[len])==0,他的最短循环子串的长度是len-net[len]。

拿第三个案例来讲

i          0   1    2   3   4   5   6

s[i]      a    b   a   b   a    b   #(#是假定的,不能输入的s的一部分)

net[i]  -1    0   0  1    2    3  4 

可以看到s[i]的长度len为6,net[6]=4,所以len-net[len]=2,正好是最小循环子串ab的长度。

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn=1000005;
int len;
char s[maxn];
int net[maxn];
void getnet()
{
    net[0]=-1;
    int k=-1;
    int j=0;
    while(j<len)
    {
        if(k==-1||s[j]==s[k])
        {
            ++j;
            ++k;
            net[j]=k;
        }
        else
            k=net[k];
    }
}
int main()
{
    while(scanf("%s",s)!=EOF)
    {
        if(s[0]=='.')break;
        len=strlen(s);
         getnet();
        if(len%(len-net[len])==0)
        {
            printf("%d\n",len/(len-net[len]));
        }
        else
            printf("1\n");//如果不能整除,就输出1,譬如abcd这样的情况,没有循环的子串
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值