Pagini recente » Cod sursa (job #1304650) | Cod sursa (job #1626860) | Cod sursa (job #1215580) | Cod sursa (job #2519849) | Cod sursa (job #1076170)
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
#define nmax 21
int n, op;
struct nod {
int apW;
int apL;
nod *next[26];
};
nod *root;
inline void init(nod *&root) {
root = new nod;
root->apW = 0;
root->apL = 0;
memset(root->next, 0, sizeof(root->next));
}
inline void insert_trie(nod *root, char a[], int n) {
for (int i = 1; i <= n; ++i) {
if (root->next[a[i] - 'a'] == NULL)
init(root->next[a[i] - 'a']);
root = root->next[a[i] - 'a'];
++root->apL;
}
++root->apW;
}
inline int query_ap(nod *root, char a[], int n) {
for (int i = 1; i <= n; ++i) {
if (root->next[a[i] - 'a'] == NULL) return 0;
root = root->next[a[i] - 'a'];
}
return root->apW;
}
char w[nmax];
inline void erase(nod *&root, int i) {
if (i == n + 1) {
--root->apW;
--root->apL;
if (!root->apL) {
delete root;
root = NULL;
}
return;
}
erase(root->next[w[i] - 'a'], i + 1);
--root->apL;
if (!root->apL) {
delete root;
root = NULL;
}
}
inline int prefix(nod *root, char a[], int n) {
for (int i = 1; i <= n; ++i) {
if (root->next[a[i] - 'a'] == NULL) return (i - 1);
root = root->next[a[i] - 'a'];
}
return n;
}
int main() {
init(root);
while (fin >> op) {
fin >> (w + 1);
n = strlen(w + 1);
if (op == 0)
insert_trie(root, w, n);
if (op == 1)
erase(root, 1);
if (op == 2)
fout << query_ap(root, w, n) << '\n';
if (op == 3)
fout << prefix(root, w, n) << '\n';
}
return 0;
}