poj 2752 Seek the Name, Seek the Fame

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
题意:
给你一个字符串s,求所有的 既是前缀 又是后缀 的 字符串 的长度。
从小到大输出,多组询问。
解:
next[]的含义:前面长度为i的字串的【前缀和后缀的最大匹配长度】
详细分析一下:【就用上面的第一个例子说明吧】


len2 = 18    next[len2] = 9 
说明对于前面长度为18的字符串,【长度为9的前缀】和【长度为9的后缀】是匹配的
也就是整个串的最大前后缀匹配长度就是9了 
所以接下来根本不需要考虑长度大于9的情况啦 

好了!既然现在只需考虑长度小于9的前后缀匹配情况,那么 
[问题就转化成蓝色串的前缀跟红色串的后缀的匹配问题了!!! 
又因为蓝串==红串 
所以问题又转化成 
找蓝串自己的前缀跟自己的后缀的最大匹配了!!! 
那么我们现在就要找next[9]的值了【next[9]的含义:蓝串的最大前后缀匹配】 

回忆第一步:我们找的是next[len2]=9【len2=18】 
怎么使得第二部目标变成9【求next[9]】呢? 
其实next[len2]=9同时可以表示为:最大匹配前后缀的【前缀长度】 
那么next[9]的意义就是: 
【主串】的最大匹配前后缀的【前缀】的【最大匹配前后缀】了!! 
也就是上面蓝串的前后缀最大匹配长度了!! 

那么算法描述就是: 
第一步:求next[len2], 即next[18] = 9; 
第二步:把9代进来,即求next[9] = 4; 
第三步:把4代进来,即求next[4] = 2; 
第四步:next[2] = 0; 也就是下标2之前的串已经没有前后缀可以匹配了 
所以答案就是: 2 4 9 18 【PS: 从小到大输出,18是串长,显然符合题意】 
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<string>
 7 #include<queue>
 8 #include<map>
 9 using namespace std;
10 const int N=4e5+18;
11 int len,ne[N],j,a[N],k;
12 char s[N];
13 void Next()
14 {
15     for(int i=0;i<=len;++i) ne[i]=0;
16     for(int i=2;i<=len;++i)
17     {
18         j=ne[i-1];
19         while(j && s[i]!=s[j+1]) j=ne[j];
20         if(s[i]==s[j+1]) ne[i]=j+1;
21     }
22     j=len;k=0;
23     while((j=ne[j])) a[++k]=j;
24     for(int i=k;i>=1;--i) cout<<a[i]<<" ";
25     cout<<len; 
26 }
27 int main()
28 {
29     while(scanf("%s",s+1)!=EOF)
30     {
31         len=strlen(s+1);
32         Next();cout<<endl;
33     }
34     return 0;
35 }
View Code

转载自:http://blog.csdn.net/guhaiteng/article/details/52108690

 
原文地址:https://www.cnblogs.com/adelalove/p/8559366.html