[hdu1686] Oulipo【KMP】

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1686

保存KMP模版,代码里P是模版串,next[]就是为它建立的。T是文本串,就是一般比较长的。next[i]表示i后缀的最长相等前缀在哪,字符串从1开始数(而不是0)。

#include <cstdio>
#include <cstring>

const int maxn = 10005, maxm = 1000005;

/* n for |Pattern|, m for |Text| */
/* |Pattern| is shorter than |Text| in general */

int kase, n, m, next[maxn];
char P[maxn], T[maxm];

/* build next[] for Pattern, not for Text!!! */
inline void get_next(void) {
	next[0] = -1;
	next[1] = 0;
	int i = 1, j = 0;
	while (i < n) {
		while (j != -1 && P[i + 1] != P[j + 1]) {
			j = next[j];
		}
		next[++i] = ++j;
	}
}
inline int count(void) {
	int i = 0, j = 0, rt = 0;
	while (j < m) {
		while (i != -1 && P[i + 1] != T[j + 1]) {
			i = next[i];
		}
		++i;
		++j;
		if (i == n) {
			++rt;
		}
	}
	
	return rt;
}

int main(void) {
	//freopen("in.txt", "r", stdin);
	scanf("%d", &kase);
	while (kase--) {
		scanf("%s", P + 1);
		n = strlen(P + 1);
		scanf("%s", T + 1);
		m = strlen(T + 1);
		
		get_next();
		printf("%d\n", count());
	}
	return 0;
}

  

posted @ 2017-05-07 19:06  ciao_sora  阅读(118)  评论(0编辑  收藏  举报