FZU 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
 
 1 #include <cstdio>

 2 #include <cstring>

 3 const int maxn = 1000010;

 4 int p[maxn],ans[maxn];

 5 char str[maxn];

 6 

 7 void get_p(int len){

 8     p[1] = 0;

 9     int j = 0;

10     for(int i = 2;i <= len;i++){

11         while(j > 0 && str[j+1] != str[i])

12             j = p[j];

13         if(str[j+1] == str[i]) 

14             j++;

15         p[i] = j;

16     }

17 }

18 

19 int main(){

20     int nkase;

21     scanf("%d",&nkase);

22     for(int kase = 1;kase <= nkase;kase++){

23         scanf("%s",str+1);

24         int len = strlen(str+1);

25         get_p(len);

26         int t = p[len],cnt = 0;

27         while(t){

28             ans[cnt++] = len-t;

29             t = p[t];

30         }

31         ans[cnt++] = len;

32         printf("Case #%d: %d\n",kase,cnt);

33         for(int i = 0;i < cnt-1;i++) 

34             printf("%d ",ans[i]);

35         printf("%d\n",ans[cnt-1]);

36     }

37     return 0;

38 }                    

 

你可能感兴趣的:(IO)