AC自动机 模板

#include
#include
#include
#include
using namespace std;
#define N 2000010
#define M 3010
queue<int> q;
char st[N];
struct {
	int p[26], s = 0, fail;
}a[M * 10];
int tot = 1;
int main() {
	int n, m, i, j;
	scanf("%d%d", &n, &m);
	for(i = 1; i <= m; i++) {
		scanf("%s", st + 1);
		int k = 1;
		for(j = 1; j <= strlen(st + 1); j++) {
			int x = st[j] - 'a';
			if(!a[k].p[x]) a[k].p[x] = ++tot;
			k = a[k].p[x];
		}
		a[k].s++;
	}
	q.push(1);
	a[1].fail = 1;
	while(!q.empty()) {
		int k = q.front();
		q.pop();
		for(i = 0; i < 26; i++) if(a[k].p[i]) { 
			int x = a[k].p[i], p = a[k].fail;
			while(p > 1 && !a[p].p[i]) p = a[p].fail;
			if(a[p].p[i] && a[p].p[i] != x) a[x].fail = a[p].p[i]; else a[x].fail = 1; 
			q.push(x);
		}
	}
	scanf("%s", st + 1);
	int k = 1, ans = 0;
	for(i = 1; i <= n; i++) {
		int x = st[i] - 'a';
		while(k > 1 && !a[k].p[x]) k = a[k].fail;
		if(a[k].p[x]) {
			k = a[k].p[x];
			int p = k;
			while(p > 1) {
				ans += a[p].s;
				p = a[p].fail;
			}
		}
	}
	printf("%d", ans);
	return 0;
}

你可能感兴趣的:(字符串-杂类,AC自动机,字符串,模板)