当前位置: 代码迷 >> 综合 >> POJ-2752 Seek the Name,Seek the Fame
  详细解决方案

POJ-2752 Seek the Name,Seek the Fame

热度:59   发布时间:2023-11-22 01:25:24.0

题目链接

http://poj.org/problem?id=2752

题目

Seek the Name, Seek the Fame
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 21465 Accepted: 11207
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,求字串T的长度length。将length按升序输出。
字串T满足:T是S的前缀,同时T还是S的后缀。

题解

考虑字符串S的前缀数组pre,pre[i]=j表示S[1..j]=S[i-j+1..i]。定义len为S的长度,x=pre[len]显然是一个解。因为S[1..x]=S[len-x+1..len],所以S[1..pre[x]]=S[len-pre[i]+1..len],也就是说pre[x]也是一个解。
综上,length=pre[len]、pre[pre[len]]…

代码

#include <cstdio>
#include <cstring>
#include <algorithm>using namespace std;
const int maxn=4e5+100;
int n,ans[maxn],tot,pre[maxn];
char t[maxn];void getpre()
{int j=0;memset(pre,0,sizeof(pre));for(int i=2;i<=n;i++){while(j>0 && t[j+1]!=t[i]) j=pre[j];if(t[j+1]==t[i]) j++;pre[i]=j;}
}int main()
{while(~scanf("%s",t+1)){n=strlen(t+1);getpre();memset(ans,0,sizeof(ans));tot=0;ans[tot]=n;for(int i=n;pre[i];i=pre[i]){int v=pre[i];ans[++tot]=v;}sort(ans,ans+tot+1);for(int i=0;i<=tot;i++){printf("%d%s",ans[i],i==tot?"\n":" ");}}return 0;
}