Solution
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
const int max_n = 1e6 + 5;
int tree[max_n][26];
int Pass[max_n];
int End[max_n];
int cnt = 1;
void insert(string word) {
int node = 1;
Pass[node]++;
for (int i = 0; i < word.length(); ++i) {
int path = word[i] - 'a';
if (tree[node][path] == 0) {
tree[node][path] = ++cnt;
}
node = tree[node][path];
Pass[node]++;
}
End[node]++;
}
int countWord(string word) {
int node = 1;
for (int i = 0; i < word.length(); ++i) {
int path = word[i] - 'a';
if (tree[node][path] == 0) return 0;
node = tree[node][path];
}
return End[node];
}
int countPre(string pre) {
int node = 1;
for (int i = 0; i < pre.length(); ++i) {
int path = pre[i] - 'a';
if (tree[node][path] == 0) return 0;
node = tree[node][path];
}
return Pass[node];
}
void delete_word(string word) {
int node = 1;
if (countWord(word) > 0) {
for (int i = 0; i < word.length(); ++i) {
int path = word[i] - 'a';
if (--Pass[tree[node][path]] == 0) {
tree[node][path] = 0;
return;
}
node = tree[node][path];
}
End[node]--;
}
}
void clear() {
memset(tree, 0, sizeof(tree));
memset(Pass, 0, sizeof(Pass));
memset(End, 0, sizeof(End));
cnt = 1;
}
int main() {
insert("Fan");
insert("Fang");
insert("Fantasy");
cout << countWord("Fan") << endl;
cout << countPre("Fa") << endl;
delete_word("Fan");
cout << countWord("Fan") << endl;
cout << countPre("Fan") << endl;
return 0;
}