Problem 1901 Period II【KMP--next数组】

版权声明:转载什么的好说,附上友链就ojek了,同为咸鱼,一起学习。 https://blog.csdn.net/sodacoco/article/details/88027217

题目:

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

题目大意:

       求 所有可以由循环得到整个字符串的 前缀的长度【循环节的最后允许欠缺】;

       即求出所有满足s[i] == s[i+p] ( 0 < i+p < len )的 p ;

解题思路:

       如果目标串的当前字符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

       例:

              aaabaaa:--> P = 4  <---> next[7] = 3

              aaabaaa:--> P = 5  <---> next[3] = 2

              aaabaaa:--> P = 6  <---> next[2] = 1

              aaabaaa:--> P = 7  <---> next[1] = 0

实现代码:

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MM=1000005;

int ne[MM],a[MM];
char mo[MM];
int lm;
void Get_next(){
    int i=0,j=-1;
    ne[0]=-1;
    while(i<lm){
        while(j!=-1&&mo[i]!=mo[j])
            j=ne[j];
        ne[++i]=++j;
    }
}
int main(){
    int ca,cas=1;
    scanf("%d",&ca);
    while(ca--){
        scanf("%s",mo);
        int k=0;
        lm=strlen(mo);
        a[k++]=lm;
        memset(ne,0,sizeof(ne));
        Get_next();
        int tmp=ne[lm];
        while(tmp){
            a[k++]=lm-tmp;
            tmp=ne[tmp];
        }
        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;
}

猜你喜欢

转载自blog.csdn.net/sodacoco/article/details/88027217