백준9250 문자열 집합 판별 작성일 2019-09-22 | In PS 문제 링크 http://icpc.me/9250 사용 알고리즘 아호 코라식 풀이 아호코라식을 구현해주면 됩니다. Trie에 kmp fail function을 접목하는 느낌으로 구현하면 됩니다. 전체 코드 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#include <bits/stdc++.h> using namespace std; typedef pair<int, int> p; struct Node{ map<char, Node*> ch; int terminal; Node() : terminal(-1) {} ~Node(){ for(auto &i : ch) delete i.second; ch.clear(); } void insert(const char *key, int num){ if(*key == 0){ terminal = num; return; } if(!ch[*key]) ch[*key] = new Node(); ch[*key]->insert(key+1, num); } Node *fail; vector<int> output; }; void aho_getFail(Node *root){ queue<Node*> q; root->fail = root; q.push(root); while(q.size()){ Node *now = q.front(); q.pop(); for(auto &i : now->ch){ Node *child = i.second; if(!child) continue; if(root == now) child->fail = root; else{ Node *t = now->fail; while(t != root && !t->ch[i.first]) t = t->fail; if(t->ch[i.first]) t = t->ch[i.first]; child->fail = t; } child->output = child->fail->output; if(child->terminal != -1){ child->output.push_back(child->terminal); } q.push(child); } } } vector<p> aho_find(string &s, Node *root){ vector<p> ret; auto state = root; for(int i=0; i<s.size(); i++){ while(state != root && !state->ch[s[i]]) state = state->fail; if(state->ch[s[i]]) state = state->ch[s[i]]; for(int j=0; j<state->output.size(); j++){ ret.push_back({i, state->output[j]}); } } return ret; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int n, q; Node *root = new Node(); cin >> n; for(int i=1; i<=n; i++){ string s; cin >> s; root->insert(s.c_str(), i); } aho_getFail(root); cin >> q; for(int i=0; i<q; i++){ string s; cin >> s; auto v = aho_find(s, root); if(v.size()) cout << "YES\n"; else cout << "NO\n"; } }