HDU 3336 Count the string

题意完全和HUST 1328一样,太感动了。

具体题解见:HUST 1328 String KMP 递增思路

由于直接复制1328的代码,没有改数组大小,re了,有点感动...

代码:

/*
*  Author:      illuz 
*  Blog:        http://blog.csdn.net/hcbbt
*  File:        hdu3336.cpp
*  Create Date: 2013-12-01 20:45:29
*  Descripton:  kmp 
*/

#include 
#include 

const int MAXN = 2e6 + 1;

int f[MAXN], ans[MAXN];
// 分别是next数组和记录影响数的数组
char P[MAXN];

void getVal(int l) {
	int i = 0, j = -1;
	f[0] = -1;
	while (i < l) {
		if (j == -1 || P[i] == P[j]) {
			i++; j++;
			f[i] = j;
		} else j = f[j];
	}
	f[0] = 0;
}

int main() {
	int t;
	scanf("%d\n", &t);
	while (t--) {
		gets(P);
		gets(P);
		int len = strlen(P);
		getVal(len);	// KMP
		long long cnt = 0;
		memset(ans, 0, sizeof(ans));
		for (int i = 1; i <= len; i++) {
			ans[i] = ans[f[i]];	// 这个字符的增加使得多少个字符也增加了
			ans[i]++;			// 这个字符也影响本身
			cnt += ans[i];
			cnt %= 10007;
		}
		printf("%lld\n", cnt);
	}
	return 0;
}


你可能感兴趣的:(=====算法相关=====,+数据结构)