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
| struct Tire { static const int ALPHABET = 26; struct Node { int len; int cnt; std::array<int, ALPHABET> next; Node() : cnt{}, next{} {} };
std::vector<Node> tr;
Tire() { init(); }
void init() { tr.assign(2, Node()); tr[0].len = -1; tr[0].next.fill(1); }
int newNode() { tr.emplace_back(); return tr.size() - 1; }
int add(const std::vector<int>& a) { int p = 1; for (auto x : a) { if (!tr[p].next[x]) { tr[p].next[x] = newNode(); tr[tr[p].next[x]].len = tr[p].len + 1; } p = tr[p].next[x]; tr[p].cnt ++ ; } return p; }
int add(const std::string& s, char offset = 'a') { std::vector<int> a(s.size()); for (int i = 0; i < (int)s.size(); i++) { a[i] = s[i] - offset; } return add(a); }
int add(const int x) { std::vector<int> a(31); for (int i = 30; i >= 0; i--) { a[30 - i] = (x >> i & 1); } return add(a); }
int next(int p, int x) { return tr[p].next[x]; }
int next(int p, char c, char offset = 'a') { return next(p, c - offset); }
int len(int p) { return tr[p].len; }
int size() { return tr.size(); }
};
|