백준9250 문자열 집합 판별

문제 링크

  • http://icpc.me/9250

사용 알고리즘

  • 아호 코라식

풀이

아호코라식을 구현해주면 됩니다.

Trie에 kmp fail function을 접목하는 느낌으로 구현하면 됩니다.

전체 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#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";
	}
}