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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章