您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  KMP next数组