ac自动机
题目链接 https://hihocoder.com/contest/hiho4/problem/1
参考:https://blog.csdn.net/baidu_30541191/article/details/47447175#
#include <iostream> #include <cstring> #include <string> #include <queue> using namespace std; struct node { node *nxt[26], *fail; int ok; node() { ok = 0; for(int i=0; i<26; i++) nxt[i]=NULL; fail=NULL; } }; const int N = 1e6 + 10; char s[N]; node *root; void ins(char *s, int len) { node *rt = root; for(int i=0; i<len; i++) { int x= s[i]-'a'; if(rt->nxt[x] == NULL) rt->nxt[x] = new node(); rt= rt->nxt[x]; } rt->ok = 1; return ; } void build() { node *rt = root; rt->fail = NULL; queue<node*> que; que.push(rt); while(!que.empty()) { node *tmp = que.front(); que.pop(); for(int i=0; i<26; i++) { if(tmp->nxt[i] != NULL) { if(tmp == root) tmp->nxt[i]->fail = root; else { node *p = tmp->fail; while(p!=NULL) { if(p->nxt[i] != NULL) { tmp->nxt[i]->fail = p->nxt[i]; break; } p = p->fail; } if(p==NULL) tmp->nxt[i]->fail = root; } que.push(tmp->nxt[i]); } } } } bool query(char *s, int len) { node *rt = root; int cnt=0; for(int i=0; i<len; i++) { int x = s[i]-'a'; while(!rt->nxt[x] && rt->fail != NULL) rt=rt->fail; rt=rt->nxt[x]; if(!rt) rt = root; node * tmp = rt; while(tmp->ok==1) { cnt++; tmp->ok = 0; tmp = tmp->fail; } } if(cnt > 0) return true; return false; } int main() { root = new node(); int n; scanf("%d",&n); for(int i=0; i<n; i++) { scanf("%s", s), ins(s, strlen(s)); } build(); scanf("%s", s); bool ok = query(s,strlen(s)); if(ok) cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; }