poj 2752Seek the Name,Seek the Fame(KMP)
来源:互联网 发布:数据库用什么软件好 编辑:程序博客网 时间:2024/06/11 05:12
Seek the Name,Seek the Fame(pku 2752)
小猫非常有名,许多夫妇翻山越岭来到Byteland为了求小猫给他们新出生的孩子赐一个名字。为了应付这项无聊的工作,具有创新精神的小猫想到了一个简单却很神奇的程序:第一步:将父亲和母亲的名字连接在一起得到一个新的字符串S。
第二部:找到一个S的子串作为前缀-后缀字符串。所谓前缀-后缀字符串即S的子串不仅是S的前缀又是S的后缀。
例如:父亲的名字是 ,母亲的名字是 ,我们可以得到字符串S是 。则S的前缀-后缀字符串有{ }。给定一个字符串S,你能帮小猫写一个程序来计算S所有可能的前缀-后缀字符串的长度吗?
输入:
输入有多组数据,每组数据为一行即上述所说的字符串S。S只包含小写英文字母且长度大于等于1小于等于400000。
输出:
对于每组数据输出一行,每行以递增的顺序输出,代表字符串S所有可能的前缀-后缀字符串的长度。
输入样例:
ababcababababcabab
aaaaa
输出样例:
2 4 9 18
1 2 3 4 5
分析:
若真正理解了KMP算法,这道题就非常简单了。我们是如何找到next函数的呢?当匹配失败时,并不是将指向模式串的指针指向0从头比较,而是指向了一个特定的位置,因为这个next[j]指向的位置前长度为next[j]的子串,同模式串第j位前的长度为next[j]的子串是相同的。这道题是让找到既能够做前缀又能做后缀的子串,那么我们可以找next[len](len为字符串的长度)前的长度为next[len]的子串,这个子串一定是前缀,又由next函数的性质可以知道这个前缀与字符串长度为next[len]的后缀是相同的,这样就找到了除字符串本身最长的满足条件的子串。同理,可以找到所有的满足条件的子串的长度。
代码:
#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int Max=400005;char str[Max];int len, next[Max], ans[Max];void get_next(){ int i = 0, j = -1; next[0] = -1; while(i < len) { if(j == -1 || str[i] == str[j]) { i++; j++; next[i] = j; } else j = next[j]; }}int main(){ while(scanf("%s", str) != EOF) { len = strlen(str); get_next(); ans[0] = len; int n = 0, i = len; while(next[i] > 0) { ans[++n] = next[i]; i = next[i]; } for(i = n; i >= 0; i--) printf("%d ", ans[i]); printf("\n"); } return 0;}
- POJ 2752 Seek the Name, Seek the Fame(KMP)
- poj 2752 Seek the Name, Seek the Fame(KMP)
- POJ-2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame(kmp)
- POJ 2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame (KMP)
- POJ 2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame (kmp)
- poj 2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame(KMP)
- POJ-2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame (KMP)
- poj 2752Seek the Name,Seek the Fame(KMP)
- POJ 2752 Seek the Name, Seek the Fame (KMP)
- POJ 2752 Seek the Name, Seek the Fame (kmp)
- poj 2752 Seek the Name, Seek the Fame(KMP)
- 1.4.PHP7.1 狐教程-女神的成长环境(Mac下 PHP开发环境 配置及安装 php7.1.x nginx mysql)
- 您正在通过不兼容的虚拟化管理程序运行 VMware Workstation。禁用此虚拟化管理程序后才能开启虚拟机
- Linux学习--磁盘分区与挂载
- 大数据江湖之即席查询与分析(上篇)--即席查询与分析的前世今生
- 线程池的原理及实现
- poj 2752Seek the Name,Seek the Fame(KMP)
- Aircrack的简单使用
- valarray类
- License Key Formatting
- csdn中让图片居中
- C++第一次实验博客:项目3 项目5
- 大数据江湖之即席查询与分析(中篇)--即席查询与分析的典型场景
- Android6.0权限封装
- 用MVC6写webapi,添加model校验过滤器