HDU3336-Count the string-KMP(next数组理解)
2015-11-07 14:15
274 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3336
好吧,对next数组还是没有理解到位,感觉有很多的出发点。还需要去更深的理解。
#include<iostream>
#include<string>
using namespace std;
string str;
int n,Next[200005];
void get_next()
{
int i=0,j=-1;
Next[0]=-1;
while(i<n){
if(j==-1||str[i]==str[j]){
i++,j++;
Next[i]=j; // 没有判断。
}else{
j=Next[j];
}
}
}
int main()
{
int t;
cin.sync_with_stdio(false);
cin>>t;
while(t--){
cin>>n>>str;
int sum=0;
get_next();
//for(int i=0;i<=n;i++) cout<<Next[i]<< ' ';cout<<endl;
for(int i=1;i<=n;i++){
int j=i;
while(j){
sum=(sum+1)%10007;
j=Next[j];
}
}
cout<<sum<<endl;
}
return 0;
}
好吧,对next数组还是没有理解到位,感觉有很多的出发点。还需要去更深的理解。
#include<iostream>
#include<string>
using namespace std;
string str;
int n,Next[200005];
void get_next()
{
int i=0,j=-1;
Next[0]=-1;
while(i<n){
if(j==-1||str[i]==str[j]){
i++,j++;
Next[i]=j; // 没有判断。
}else{
j=Next[j];
}
}
}
int main()
{
int t;
cin.sync_with_stdio(false);
cin>>t;
while(t--){
cin>>n>>str;
int sum=0;
get_next();
//for(int i=0;i<=n;i++) cout<<Next[i]<< ' ';cout<<endl;
for(int i=1;i<=n;i++){
int j=i;
while(j){
sum=(sum+1)%10007;
j=Next[j];
}
}
cout<<sum<<endl;
}
return 0;
}
相关文章推荐
- KMP算法的C#实现方法
- JavaScript中数据结构与算法(五):经典KMP算法
- 字符串算法--KMP--Java实现
- KMP算法(转载)
- kmp算法实现
- KMP算法详解
- linux kernel data struct: KMP算法实现
- 求一个字符串中连续出现次数最多的子串
- KMP算法总结
- KMP字符串匹配算法
- 字符串匹配之KMP算法
- kmp
- 【hiho一下第三周】KMP计算模式串在原串出现次数
- HDU1711 模板题-KMP
- HDU1358:Period
- hdu1711
- POJ 2406 Power Strings
- KMP next[]数组
- kmp 学习 hihocoder #1015
- PHP展示KMP拓展算法思想