2016夏季练习——KMP
2016-07-26 00:50
357 查看
来源:HDU3336
注意KMP的next表和自身前缀的关系,还有就是注意我们从0开始打表的话实际上我们是有第len号的next表项,此表项必然是表示全部字符串。
当next表为0的时候,我们容易知道此时是失配的情况。
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MOD = 10007;
const int STRLEN = 200000;
int n;
char str[STRLEN];
int nxt[STRLEN];
int len;
void get_next(){
int i,j;
i=0;
j=nxt[0]=-1;
while(i<len){
while(j!=-1&&str[i]!=str[j]) j=nxt[j];
nxt[++i] = ++j;
}
// cout<<"next"<<endl;
// for(int i=0;i<=len;i++){
// cout<<nxt[i]<<" ";
// }
// cout <<endl;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
scanf("%s",str);
len = strlen(str);
get_next();
int ans=0;
for(int i=1;i<=len;i++){
int t=i;
// t = nxt[t];
while(t){//t为0对应的是失配的确情况,所以不算在内
ans=(ans+1)%MOD;
t=nxt[t];
}
}
cout<<ans<<endl;
}
return 0;
}
注意KMP的next表和自身前缀的关系,还有就是注意我们从0开始打表的话实际上我们是有第len号的next表项,此表项必然是表示全部字符串。
当next表为0的时候,我们容易知道此时是失配的情况。
代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MOD = 10007;
const int STRLEN = 200000;
int n;
char str[STRLEN];
int nxt[STRLEN];
int len;
void get_next(){
int i,j;
i=0;
j=nxt[0]=-1;
while(i<len){
while(j!=-1&&str[i]!=str[j]) j=nxt[j];
nxt[++i] = ++j;
}
// cout<<"next"<<endl;
// for(int i=0;i<=len;i++){
// cout<<nxt[i]<<" ";
// }
// cout <<endl;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
scanf("%s",str);
len = strlen(str);
get_next();
int ans=0;
for(int i=1;i<=len;i++){
int t=i;
// t = nxt[t];
while(t){//t为0对应的是失配的确情况,所以不算在内
ans=(ans+1)%MOD;
t=nxt[t];
}
}
cout<<ans<<endl;
}
return 0;
}
相关文章推荐
- Uva-11324 The Largest Clique(强连通分量缩点+DAGdp)
- POJ-----1363栈的模拟
- SCU 4524 Division(强连通分量+缩点+最小路径覆盖)
- 浑浑噩噩又一天
- 万能适配器终结
- Maven 指定JDK版本
- 走遍世界 —— 加拿大
- NYOJ-201-作业题
- Referrer 还是 Referer?
- hosts文件
- CSS —— z-index与background重叠研究
- 图论求割点模板
- 城堡中的美女(2)
- Http 请求头中的 Proxy-Connection
- 关于硬连接和符号连接的理解
- jdk jre java虚拟机 GCjava回收机制
- C++——虚继承(4)
- 四大“互联网+”企业营销模式
- Git使用
- 蒙特卡罗方法求非概率分布的随机数