next数组求所有可能的循环节长度

For each prefix with length P of a given string S,if

S[i]=S[i+P] for i in [0..SIZE(S)-p-1],

then the prefix is a “period” of S. We want to all the periodic prefixs.

Input

Input contains multiple cases.

The first line contains an integer T representing the number of cases. Then following T cases.

Each test case contains a string S (1 <= SIZE(S) <= 1000000),represents the title.S consists of lowercase ,uppercase letter.

Output

For each test case, first output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of periodic prefixs.Then output the lengths of the periodic prefixs in ascending order.

Sample Input

4
ooo
acmacmacmacmacma
fzufzufzuf
stostootssto

Sample Output

Case #1: 3
1 2 3
Case #2: 6
3 6 9 12 15 16
Case #3: 4
3 6 9 10
Case #4: 2
9 12

就是求出所有可能的循环节的长度

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MM=1000005;
#define mem(a,b) memset(a,b,sizeof(a))

int next[MM],a[MM];
char str[MM];
int len;
void Get_nextxt()
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<len)
    {
        while(j!=-1&&str[i]!=str[j])
            j=next[j];
        next[++i]=++j;
    }
}
int main()
{
    int ca,cas=1;
    scanf("%d",&ca);
    while(ca--)
    {

        scanf("%s",str);
        int k=0;
        len=strlen(str);
        a[k++]=len;
        mem(next,0);
        Get_nextxt();
        int temp=next[len];
        while(temp)
        {
            a[k++]=len-temp;
            temp=next[temp];
        }
        printf("Case #%d: %d\n",cas++,k);
        for(int i=1; i<k; i++)
            printf("%d ",a[i]);
        printf("%d\n",a[0]);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值