[USACO15FEB]审查(黄金)Censoring (Gold)

题面

传送门

Sol

AC自动机+栈,每次匹配到栈顶减去这个单词的长度,回到之前的状态
最后栈中留下的就是答案

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e5 + 5);

int ch[26][_], tot, fail[_], len[_], n, m, top;
char s[_], w[_];
struct Stack{  char c; int x;  } S[_];
queue <int> Q;

IL void Insert(){
	RG int l = strlen(w), x = 0;
	for(RG int i = 0; i < l; ++i){
		RG int c = w[i] - 'a';
		if(!ch[c][x]) ch[c][x] = ++tot;
		x = ch[c][x];
	}
	len[x] = l;
}

IL void GetFail(){
	for(RG int i = 0; i < 26; ++i) if(ch[i][0]) Q.push(ch[i][0]);
	while(!Q.empty()){
		RG int fa = Q.front(); Q.pop();
		for(RG int i = 0; i < 26; ++i)
			if(ch[i][fa]) fail[ch[i][fa]] = ch[i][fail[fa]], Q.push(ch[i][fa]);
			else ch[i][fa] = ch[i][fail[fa]];
	}
}

int main(RG int argc, RG char* argv[]){
	scanf(" %s%d", s, &n); m = strlen(s);
	for(RG int i = 1; i <= n; ++i) scanf(" %s", w), Insert();
	GetFail();
	for(RG int i = 0, x = 0; i < m; ++i){
		x = ch[s[i] - 'a'][x]; S[++top] = (Stack){s[i], x};
		if(len[x]) top -= len[x], x = S[top].x;
	}
	m = 0; while(top) s[++m] = S[top--].c;
	for(RG int i = m; i; --i) printf("%c", s[i]);
	return 0;
}

原文地址:https://www.cnblogs.com/cjoieryl/p/8330638.html