【BZOJ3670】[Noi2014]动物园【KMP】【fail树】

【题目链接】

先求出fail数组,然后在fail树上做个前缀和,然后直接统计就行了。。

/* Pigonometry */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 1000005, p = 1000000007;

int n, fail[maxn], cnt[maxn];
char s[maxn];

inline void getfail() {
	fail[1] = 0; cnt[1] = 1;
	for(int i = 2, j = 0; i <= n; fail[i] = j, cnt[i] = cnt[j] + 1, i++) {
		for(; j != 0 && s[i] != s[j + 1]; j = fail[j]);
		if(s[i] == s[j + 1]) j++;
	}
}

inline int getnum() {
	int res = 1;
	for(int i = 2, j = 0; i <= n; i++) {
		for(; j != 0 && s[i] != s[j + 1]; j = fail[j]);
		if(s[i] == s[j + 1]) j++;
		for(; i - j < j; j = fail[j]);
		res = (LL)res * (cnt[j] + 1) % p;
	}
	return res;
}

int main() {
	int T; scanf("%d", &T);
	while(T--) {
		scanf("%s", s + 1); n = strlen(s + 1);
		getfail();
		printf("%d\n", getnum());
	}
	return 0;
}


你可能感兴趣的:(【BZOJ3670】[Noi2014]动物园【KMP】【fail树】)