POJ_2752 Seek the Name, Seek the Fame KMP

Posted dybala21

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ_2752 Seek the Name, Seek the Fame KMP相关的知识,希望对你有一定的参考价值。

一、题目

  POJ2752

二、分析

  比较明显的KMP运用。

  但是这题不是只找一个,仔细看题后可以发现相当于是在找到最大的满足条件的后缀后,再在这个后缀里面找满足条件的后缀。

  可以不断的运用KMP得出答案,但是会超时。

  寻找优化,发现答案在处理过的next数组中,因为题目中的条件就是前缀和后缀交集,那么前缀的串肯定与后缀的串相同,那么我们只需要改变长度继续分析就可以了。

三、AC代码

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <set>
 5 using namespace std;
 6 const int maxn = 4e5 + 14;
 7 char s[maxn];
 8 int Next[maxn], Len;
 9 int ans[maxn], cnt;
10 
11 void get_next()
12 
13     Next[0] = -1;
14     int i = 0, j = -1;
15     while(i <= Len)
16     
17         if(j == -1 || s[i] == s[j])
18         
19             i++;
20             j++;
21             Next[i] = j;
22         
23         else
24         
25             j = Next[j];
26         
27     
28 
29 
30 void solve()
31 
32     get_next();
33     cnt = 0;
34     while(Len > 0)
35     
36         ans[cnt++] = Len;
37         Len = Next[Len];
38     
39     cnt--;
40     while(cnt > 0)
41     
42         printf("%d ", ans[cnt--]);
43     
44     printf("%d\n", ans[0]);
45 
46 
47 int main()
48 
49     //freopen("input.txt", "r", stdin);
50     while(scanf("%s", s) != EOF)
51     
52         Len = strlen(s);
53         solve();
54     
55     return 0;
56 

 

以上是关于POJ_2752 Seek the Name, Seek the Fame KMP的主要内容,如果未能解决你的问题,请参考以下文章