题目链接
ac自动机模板题
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <queue>
using namespace std;
const int N = 1e6 + 5;
struct Trie
{
int next[N][26], ed[N], fail[N], root, pos;
int newnode()
{
for(int i = 0; i < 26; i++)
next[pos][i] = -1;
ed[pos] = 0;
return pos++;
}
void init()
{
pos = 0;
root = newnode();
}
void insert(string s)
{
int n = s.size();
int now = root;
for(int i = 0; i < n; i++)
{
int b = s[i] - 'a';
if(next[now][b] == -1) next[now][b] = newnode();
now = next[now][b];
}
ed[now]++;
}
void build()
{
int now = root;
queue<int> Q;
fail[root] = root;
for(int i = 0; i < 26; i++)
{
if(next[now][i] == -1)
next[now][i] = root;
else
{
fail[next[now][i]] = root;
Q.push(next[now][i]);
}
}
while(!Q.empty())
{
int now = Q.front(); Q.pop();
for(int i = 0; i < 26; i++)
{
if(next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else
{
fail[next[now][i]] = next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
}
int query(string s)
{
int n = s.size();
int now = root;
int ans = 0;
for(int i = 0; i < n; i++)
{
int b = s[i]-'a';
now = next[now][b];
int tmp = now;
while(tmp != root)
{
if(ed[tmp] >= 0)
{
ans += ed[tmp];
ed[tmp] = -1;
}
else
break;
tmp = fail[tmp];
}
}
return ans;
}
};
Trie ac;
int n;
string tmp;
int main()
{
ac.init();
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
cin >> tmp;
ac.insert(tmp);
}
getchar();
ac.build();
getline(cin,tmp);
int ans = ac.query(tmp);
if(ans == 0)
printf("NO\n");
else
printf("YES\n");
return 0;
}