poj 2752 kmp

Seek the Name, Seek the Fame
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 23027   Accepted: 12001

Description

The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm: 

Step1. Connect the father's name and the mother's name, to a new string S. 
Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S). 

Example: Father='ala', Mother='la', we have S = 'ala'+'la' = 'alala'. Potential prefix-suffix strings of S are {'a', 'ala', 'alala'}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:) 

Input

The input contains a number of test cases. Each test case occupies a single line that contains the string S described above. 

Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000. 

Output

For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby's name.

Sample Input

ababcababababcabab
aaaaa

Sample Output

2 4 9 18
1 2 3 4 5

题意:字符串的后缀跟前缀相同时,输出相同字符长度。
如:
ababcababababcabab
前面两个ab与最后的两个ab匹配有2
abab与后面的abab匹配,有4
以此类推有9与18。
其中18肯定是存在的。
现在对于前面的匹配,只需要借助kmp的next数组,从后向前滚动,判断当前字符是否与字符串最后一个字符是否相同,相同就存入答案输出中。

 1 #include<cstdio>
 2 #include<cstring>
 3 using namespace std;
 4 const int maxn=400006;
 5 char a[maxn];
 6 int next[maxn],out[maxn];
 7 int n;
 8 
 9 void get_next()
10 {
11     next[0]=-1;
12     int temp=-1,i=0;
13     while(i!=n){
14         if(temp==-1 || a[i]==a[temp])
15             next[++i]=++temp;
16         else  temp=next[temp];
17     }
18 }
19 
20 int main()
21 {
22     while( ~scanf("%s",a)){
23         n=strlen(a);
24         get_next();
25         int cnt=0;
26         int t=next[n-1];
27         while(t!=-1){
28             if(a[t]==a[n-1])
29                 out[cnt++]=t+1;
30             t=next[t];
31         }
32         for(int i=cnt-1;i>=0;i--)
33             printf("%d ",out[i]);
34         printf("%d
",n);
35     }
36     return 0;
37 }
 
原文地址:https://www.cnblogs.com/ZQUACM-875180305/p/9284405.html