`
bcyy
  • 浏览: 1809439 次
文章分类
社区版块
存档分类
最新评论

hdu 3336(KMP)

 
阅读更多

http://acm.hdu.edu.cn/showproblem.php?pid=3336

/*

KMP中next数组的使用,可以加深对next数组的理解。

学习KMP时看到两篇不错的博客,推荐给大家

http://www.cnblogs.com/wuyiqi/archive/2012/01/05/2313746.html

http://blog.csdn.net/niushuai666/article/details/6960985

*/

题目:求给定字符串中包含的前缀总数。

#include"iostream"
#include"string"
using namespace std;
#define Max 200005
char s[Max];
int next[Max],ans;
void GetNext(int n)
{
	int i,j;
	for(i=0,j=-1,next[0]=-1;i<n;){
		if(j==-1||s[i]==s[j]){
			i++;
			j++;
			next[i]=j;
		}
		else{
			j=next[j];
		}
	}
}
int main()
{
	int t,n,i,j;
	cin>>t;
	while(t--){
		cin>>n>>s;
		GetNext(n);
		for(i=1,ans=n;i<=n;i++){//next数组的值填充到n而不是n-1;
			j=i;
			while(next[j]!=0){
				ans++;
				j=next[j];
				ans%=10007;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics