FZU 1901+kmp的next数组的应用

本文介绍了一种算法,用于找出给定字符串的所有周期性前缀,并提供了完整的C++实现代码。该算法通过构建字符串的前缀表并利用KMP算法的思想来高效地解决问题。

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

Accept: 122    Submit: 330
Time Limit: 1000 mSec    Memory Limit : 32768 KB

Problem 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

4oooacmacmacmacmacmafzufzufzufstostootssto

Sample Output

Case #1: 31 2 3Case #2: 63 6 9 12 15 16Case #3: 43 6 9 10Case #4: 29 12 
解决方案:首先,整条串必须要有。然后把整串的所以前缀求出来,用串长减去前缀的长度即为其余的答案
code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#define MMAX 1000004
using namespace std;
char text[MMAX];
int next[MMAX];
void get_next()
{
    next[0]=-1;
    int j=-1,i=0;
    while(text[i]!='\0')
    {
        if(j==-1||text[i]==text[j])
        {
            i++,j++;
            next[i]=j;
        }
        else j=next[j];
    }
}
int main()
{
    int t,k=0;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",text);
        int len=strlen(text);

        get_next();

        stack<int> S;
        S.push(len);
        int j=len;
        while(next[j]>=1)
        {

            j=next[j];
             S.push(j);
        }
        printf("Case #%d: %d\n",++k,S.size());
        j=len;
        while(next[j]>=1)
        {

            j=next[j];
            printf("%d ",len-j);
        }
        printf("%d\n",len);

    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值