当前位置: 代码迷 >> 综合 >> poj 2752 Seek the Name, Seek the Fame(KMP 失配函数用法)
  详细解决方案

poj 2752 Seek the Name, Seek the Fame(KMP 失配函数用法)

热度:57   发布时间:2024-01-13 21:03:12.0

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

2、题目大意:

给定多组样例,每组样例有一个字符串,求这个字符串的前缀字符串,并输出位置,并且这些前缀字符串同时也是后缀字符串,

3、用KMP失配函数,求出每一个模式值,递归输出即可

4、题目:

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

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

Source

POJ Monthly--2006.01.22,Zeyuan Zhu
5、代码:

#include<stdio.h>
#include<string.h>
#define N 400005
char str[N];
int f[N];
int ans[N];
//KMP 失配函数
void getFail(char *p, int *f)
{int m=strlen(p);f[0]=f[1]=0;for(int i=1; i<m; ++i){int j=f[i];while(j && p[i]!=p[j])j=f[j];f[i+1] = p[i]==p[j]?1+j:0;}
}
int main()
{while(scanf("%s",str)!=EOF){getFail(str,f);int len=strlen(str);
//        for(int i=0;i<=len;i++)
//        printf("%d %d\n",i,f[i]);int j=0;//递归输出while(len!=0){ans[j++]=len;len=f[len];}for(int i=j-1;i>=0;i--)printf("%d ",ans[i]);printf("\n");}return 0;
}