首页 > 代码库 > POJ 2752 Seek the Name, Seek the Fame

POJ 2752 Seek the Name, Seek the Fame

题目链接:http://poj.org/problem?id=2752

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

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

ababcababababcababaaaaa

Sample Output

2 4 9 181 2 3 4 5

题目大意:给定一个字符串输出其中既是前缀又是后缀的子串的长度
解题思路:借助KMP算法中的next数组
next[i]的值表明在字符串中i之前的子串长度为next[i]的前缀和后缀相同

下标

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

 

字符串

a

b

a

b

c

a

b

a

b

a

b

a

b

c

a

b

a

b

 

Next[i]

0

0

1

2

0

1

2

3

4

3

4

3

4

5

6

7

8

9

 

 

AC代码:
技术分享
 1 #include <stdio.h> 2 #include <string.h> 3 int next[400010]; 4 char str[400010]; 5 void getnext()  //先求出next数组 6 { 7     int i = 0,j = -1; 8     next[0] = -1; 9     int len = strlen(str);10     while (i < len)11     {12         if (j == -1 || str[i]==str[j])13         {14             ++ i;15             ++ j;16             next[i] = j;17         }18         else19             j = next[j];20     }21 }22 int main()23 {24     int num[400010],i,k;25     while (scanf("%s",str)!=EOF)26     {27         int len = strlen(str);28         getnext();29         num[0] = len;30         k = 1;31         while (next[num[k-1]]) //借助next数组将既是前缀有是后缀的子串的长度32         {33             num[k] = next[num[k-1]];34             k ++;35         }36         for (i = k-1; i > 0; i --)37             printf("%d ",num[i]);38         printf("%d\n",num[0]);39     }40     return 0;41 }
View Code

 



POJ 2752 Seek the Name, Seek the Fame