【BZOJ3940】[Usaco2015 Feb]Censoring【AC自动机 / KMP】

【题目链接】

【BZOJ3942题解】的加强版,但是没有什么区别。

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

using namespace std;

const int maxn = 1000005, maxq = maxn;

int n, pos[maxn], q[maxq];
char s[maxn], str[maxn], ans[maxn];

int son[maxn][26], fail[maxn], acmcnt, flag[maxn];

inline void insert() {
	int now = 0, len = strlen(str);
	for(int i = 0; i < len; i++) {
		int &pos = son[now][str[i] - 'a'];
		if(!pos) pos = ++acmcnt;
		now = pos;
	}
	flag[now] = max(flag[now], len);
}

inline void getfail() {
	int h = 0, t = 0;
	for(int i = 0; i < 26; i++) if(son[0][i]) q[t++] = son[0][i];
	while(h != t) {
		int u = q[h++];
		for(int i = 0; i < 26; i++)
			if(!son[u][i]) son[u][i] = son[fail[u]][i];
			else {
				fail[q[t++] = son[u][i]] = son[fail[u]][i];
				flag[son[u][i]] = max(flag[son[u][i]], flag[fail[son[u][i]]]);
			}
	}
}

int main() {
	scanf("%s%d", s, &n);
	for(int i = 1; i <= n; i++) {
		scanf("%s", str);
		insert();
	}
	getfail();

	int now = 0, tot = 0, len = strlen(s);
	for(int i = 0; i < len; i++) {
		now = son[now][s[i] - 'a']; ans[tot] = s[i];
		pos[tot] = now; tot++;
		if(flag[now]) {
			tot -= flag[now];
			now = pos[tot - 1];
		}
	}
	ans[tot] = '\0';

	printf("%s\n", ans);
	return 0;
}



你可能感兴趣的:(【BZOJ3940】[Usaco2015 Feb]Censoring【AC自动机 / KMP】)