码迷,mamicode.com
首页 > 其他好文 > 详细

POJ_2752 Seek the Name, Seek the Fame 【KMP】

时间:2019-07-15 17:31:45      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:else   mil   sans   cstring   put   size   题目   int   ret   

一、题目

  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】

标签:else   mil   sans   cstring   put   size   题目   int   ret   

原文地址:https://www.cnblogs.com/dybala21/p/11189975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!