2016夏季练习——KMP
2016-07-25 10:35
253 查看
来源:POJ2752
KMP的一个运用,关键是要理解next指针
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
string str;
const int MAXN = 400000+10;
int nxt[MAXN];
int len;
void get_next(){
int i,j;
memset(nxt,0,sizeof(nxt));
i = 0;
nxt[0] = -1;
j=-1;
// cout<<"len: "<<len<<endl;
while(i<len){
// cout<<"j: "<<j<<endl;
if(j==-1 || str[i]==str[j]){
i++;
j++;
nxt[i] = j;
}
else{
j = nxt[j];
}
}
}
int ans[MAXN];
int main(){
//理解next数组的意义的话,其实这个就是从最后不断向前跳转的next序列
//next[j]数组的理解是:s[0~t]和s[j-t~j]匹配的最大的t
//那么这样的前缀我已经有了,所以只要保证s[j-t~j]是后缀就行
//那么这个题目就结束了
while(cin>>str){
len = str.length();
// cout<<str<<endl;
get_next();
int k=nxt[len-1];
int cnt=0;
while(k!=-1){
if(str[k]==str[len-1]){
//cout<<"yes"<<endl;
ans[cnt++] = 1+k;
}
k = nxt[k];
//cout<<k<<endl;
}
for(int i=cnt-1;i>=0;i--){
cout<<ans[i]<<" ";
}
cout<<len<<endl;//串本身必然成立
}
return 0;
}
KMP的一个运用,关键是要理解next指针
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
string str;
const int MAXN = 400000+10;
int nxt[MAXN];
int len;
void get_next(){
int i,j;
memset(nxt,0,sizeof(nxt));
i = 0;
nxt[0] = -1;
j=-1;
// cout<<"len: "<<len<<endl;
while(i<len){
// cout<<"j: "<<j<<endl;
if(j==-1 || str[i]==str[j]){
i++;
j++;
nxt[i] = j;
}
else{
j = nxt[j];
}
}
}
int ans[MAXN];
int main(){
//理解next数组的意义的话,其实这个就是从最后不断向前跳转的next序列
//next[j]数组的理解是:s[0~t]和s[j-t~j]匹配的最大的t
//那么这样的前缀我已经有了,所以只要保证s[j-t~j]是后缀就行
//那么这个题目就结束了
while(cin>>str){
len = str.length();
// cout<<str<<endl;
get_next();
int k=nxt[len-1];
int cnt=0;
while(k!=-1){
if(str[k]==str[len-1]){
//cout<<"yes"<<endl;
ans[cnt++] = 1+k;
}
k = nxt[k];
//cout<<k<<endl;
}
for(int i=cnt-1;i>=0;i--){
cout<<ans[i]<<" ";
}
cout<<len<<endl;//串本身必然成立
}
return 0;
}
相关文章推荐
- 石子合并
- PHP 5.4 的 Trait 特性_实现类的多重继承
- 数据结构——树的术语
- 推荐一个好用的表格插件Bootstrap Table
- TCP/IP详解学习笔记 这位仁兄写得太好了.
- vecor预分配内存溢出2
- 让VS2013添加新类时自动添加public关键字
- 2016/7/25 D180C SPI flash增加代码记录
- 动态路由 RIP
- 细谈select函数(C语言)
- 细谈select函数(C语言)
- 微信接口CSDN博客
- java学习资源分享
- jvm类加载器
- Count and Say
- 在JS中用EL表达式访问request作用域里面的值得问题
- DB2 新增主键
- form表单关闭历史记录
- 7.20_计算机基础知识
- nncq---后台所有文章添加一个发布日期修改