FZU Problem 1901 Period II

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

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


题意:给你一个字符串str,对于每个str长度为p的前缀,如果str[i]==str[p+i](p+i<len),那么我们认为它是一个periodic prefixs.求所有满足题意的前缀的长度p。
知识点:KMP算法、对next数组的理解
KMP算法中next数组的含义是什么?
next数组:失配指针
如果目标串的当前字符i在匹配到模式串的第j个字符时失配,那么我们可以让i试着去匹配next(j)
对于模式串str,next数组的意义就是:
如果next(j)=t,那么str[1…t]=str[len-t+1…len]
我们考虑next(len),令t=next(len);
next(len)有什么含义?
str[1…t]=str[len-t+1…len]
那么,长度为len-next(len)的前缀显然是符合题意的。
接下来我们应该去考虑谁?
t=next( next(len) );
t=next( next (next(len) ) );
 一直下去直到t=0,每个符合题意的前缀长是len-t
#include <cstdio>
#include <cstring>
const int maxn = 1000010;
int p[maxn],ans[maxn];
char str[maxn];

void get_p(int len){
    p[1] = 0;
    int j = 0;
    for(int i = 2;i <= len;i++){
        while(j > 0 && str[j+1] != str[i])  j = p[j];
        if(str[j+1] == str[i])  j++;
        p[i] = j;
    }
}

int main(){
    int nkase;
    scanf("%d",&nkase);
    for(int kase = 1;kase <= nkase;kase++){
        scanf("%s",str+1);
        int len = strlen(str+1);
        get_p(len);
        int t = p[len],cnt = 0;
        while(t){
            ans[cnt++] = len-t;
            t = p[t];
        }
        ans[cnt++] = len;
        printf("Case #%d: %d\n",kase,cnt);
        for(int i = 0;i < cnt-1;i++)  printf("%d ",ans[i]);
        printf("%d\n",ans[cnt-1]);
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值