FZU 1901 Period II

本文介绍了一种求解字符串所有循环节的方法。通过构建Next数组并遍历字符串,找到所有符合条件的循环节长度,并按升序输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
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


【题目大意】
求一个字符串的所有的循环节。


【题目分析】
    显然,整个字符串的循环节是比较简单的,即l-ne[l],那么我们考虑一下如何求出所有的循环节,这样子求出整个字符串的循环节之后,我们可以想象到,整个字符串分成两个部分,前面和后面(这句是废话)。对于分割点k 可以知道s[1]=s[k+1]…以此类推,那么前半部分的循环节同样也是ne[k],那么我们只需要不断的next,直到不能继续位置,然后用总长减去ne[j]就是循环节的所有情况了。
   


【代码】

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
char a[1000001];
int ne[1000001],kase=0,out[1000001];
int main()
{
    int tt;
    scanf("%d",&tt);
    while (tt--)
    {
        scanf("%s",a+1);
        int l=strlen(a+1);
        for (int i=2,j=0;i<=l;++i)
        {
            while (j&&a[j+1]!=a[i]) j=ne[j];
            if (a[j+1]==a[i]) j++;
            ne[i]=j;
        }
        int ans=0,p=l,top=0;
        while (p)
        {
            ans++;
            p=ne[p];
            out[++top]=p;
        }
        printf("Case #%d: %d\n",++kase,ans);
        p=l;
        for (int i=1;i<=top;++i)
            if (i!=top)
                printf("%d ",l-out[i]);
            else printf("%d",l-out[i]);
        printf("\n");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值