题意:给定n个模式串和一个文本串,判断文本中是否存在模式串。
思路:套模板即可。
AC代码
#include <cstdio>
#include <cmath>
#include <cctype>
#include <bitset>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
typedef long long LL;
const int maxn = 1e6 + 5;
struct Aho{
struct State{
int next[26];
int fail, cnt;
}state[maxn];
queue<int>que;
int size;
void init() {
size = 1;
while(!que.empty()) que.pop();
for(int i = 0; i < maxn; ++i) {
memset(state[i].next, 0, sizeof(state[i].next));
state[i].cnt = state[i].fail = 0;
}
}
void insert(char *S) {
int n = strlen(S);
int now = 0;
for(int i = 0; i < n; ++i) {
int num = S[i]-'a';
if(state[now].next[num]) now = state[now].next[num];
else {
state[now].next[num] = size++;
now = state[now].next[num];
}
}
state[now].cnt++;
}
void getFail() {
state[0].fail = -1;
que.push(0);
while(!que.empty()) {
int u = que.front(); que.pop();
for(int i = 0; i < 26; ++i) {
if(state[u].next[i]) {
if(u == 0) state[state[u].next[i]].fail = 0;
else {
int v = state[u].fail;
while(v != -1 && !state[v].next[i]) v = state[v].fail;
if(v == -1) state[state[u].next[i]].fail = -1;
else state[state[u].next[i]].fail = state[v].next[i];
}
que.push(state[u].next[i]);
}
}
}
}
int Get(int u) {
int res = 0;
while(u) {
res += state[u].cnt;
state[u].cnt = 0;
u = state[u].fail;
}
return res;
}
bool match(char *S) {
int n = strlen(S);
int now = 0, res = 0;
for(int i = 0; i < n; ++i) {
int num = S[i]-'a';
if(state[now].next[num]) now = state[now].next[num];
else {
int u = state[now].fail;
while(u != -1 && !state[u].next[num]) u = state[u].fail;
if(u == -1) now = 0;
else now = state[u].next[num];
}
if(state[now].cnt) res += Get(now);
if(res) return true;
}
return false;
}
}aho;
char S[maxn];
int n;
int main() {
while(scanf("%d", &n) == 1) {
aho.init();
for(int i = 0; i < n; ++i) {
scanf("%s", S);
aho.insert(S);
}
aho.getFail();
scanf("%s", S);
if(aho.match(S)) printf("YES\n");
else printf("NO\n");
}
return 0;
}
如有不当之处欢迎指出!