-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie_matching.cpp
122 lines (99 loc) · 1.81 KB
/
trie_matching.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Node {
int next[4];
Node ()
{
fill(next, next + 4, -1);
}
bool isLeaf () const
{
return (next[0] == -1 && next[1] == -1 && next[2] == -1 && next[3] == -1);
}
};
static int letterToIndex(char letter)
{
switch (letter) {
case 'A':
return 0;
case 'C':
return 1;
case 'G':
return 2;
case 'T':
return 3;
default:
assert(false);
return -1;
}
}
static vector<Node> create_trie(const vector <string> &patterns)
{
vector<Node> trie(1);
for (size_t i = 0; i < patterns.size(); i++) {
const string &pattern = patterns[i];
int v = 0;
for (size_t j = 0; j < pattern.size(); j++) {
char c = pattern[j];
int c_i = letterToIndex(c);
int w = trie[v].next[c_i];
if (w != -1) {
v = w;
} else {
w = trie.size();
trie.push_back(Node());
trie[v].next[c_i] = w;
v = w;
}
}
}
return trie;
}
static vector <int> solve(const string &text, const vector <string> &patterns)
{
vector <int> result;
vector<Node> trie;
trie = create_trie(patterns);
for (size_t i = 0; i < text.size(); i++) {
int v = 0;
size_t j = i;
while (true) {
if (trie[v].isLeaf()) {
result.push_back(i);
break;
}
if (j >= text.size()) break;
char c = text[j++];
int c_i = letterToIndex(c);
v = trie[v].next[c_i];
if (v == -1) break;
}
}
return result;
}
int main(void)
{
string text;
cin >> text;
int n;
cin >> n;
vector <string> patterns (n);
for (int i = 0; i < n; i++) {
cin >> patterns[i];
}
vector <int> ans = solve(text, patterns);
for (int i = 0; i < (int) ans.size (); i++) {
cout << ans[i];
if (i + 1 < (int) ans.size ()) {
cout << " ";
} else {
cout << endl;
}
}
return 0;
}