HDU 3336 Count the string (KMP + 出现次数)

题目链接

题意:给一个长度为n的字符串,求每个前缀在字符串中的出现次数的和,答案模10007。

分析:kmp水题,按顺序遍历每个前缀,当前缀出现的次数为1,后面肯定都为1。

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
const double eps=1e-6;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int mod=10007;
const int maxn=2e5+10;

int nx[maxn];
void getnx(string x){
	int m=x.size();
	int i,j;
	j=nx[0]=-1;
	i=0;
	while (i<m){
		while (-1!=j && x[i]!=x[j]) j=nx[j];
		if (x[++i]==x[++j]) nx[i]=nx[j];
		else nx[i]=j;
	}
}

int kmp_count(string s, string t){
	int n=s.size();
	int m=t.size();
	int i=0,j=0,ans=0;
	getnx(t);
	while (i<n){
		while (-1!=j && s[i]!=t[j]) j=nx[j];
		i++;
		j++;
		if (j>=m){
			ans++;
			j=nx[j];  //如果不可重叠,将此处改为  j=0;
		}
	}
	return ans;
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int T;
	cin>>T;
	while (T--){
		int n;
		cin>>n;
		string s;
		cin>>s;
		ll ans=0;
		//getnx(s);
		for (int i=1; i<=n; i++){
			string t=s.substr(0,i);
			ll tmp=kmp_count(s,t);
			//cout<<t<<endl;
			//cout<<tmp<<endl;			
			if (tmp==1) {
				ans+=n-i+1;
				break;
			}
			ans=(ans+tmp)%mod;
		}
		cout<<ans%mod<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值