Pagini recente » Cod sursa (job #720336) | Cod sursa (job #1423255) | Cod sursa (job #1206706) | Cod sursa (job #2600241) | Cod sursa (job #1132536)
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int i, j, n;
int op;
char a[26];
struct nod {
int w;
int l;
nod *next[26];
};
nod *R;
void init(nod *&R) {
R = new nod;
R->w = 0;
R->l = 0;
memset(R->next, 0, sizeof(R->next));
}
void insert(nod *R, char a[], int n) {
for (int i = 1; i <= n; ++i) {
if (R->next[a[i] - 'a'] == NULL)
init(R->next[a[i] - 'a']);
R = R->next[a[i] - 'a'];
++R->l;
}
++R->w;
}
int nrAp(nod *R, char a[], int n) {
for (int i = 1; i <= n; ++i) {
if (R->next[a[i] - 'a'] == NULL) return 0;
R = R->next[a[i] - 'a'];
}
return R->w;
}
void erase(nod *&R, int i) {
if (i == n + 1) {
--R->l;
--R->w;
if (R->l == 0) {
delete R;
R = NULL;
}
return;
}
erase(R->next[a[i] - 'a'], i + 1);
--R->l;
if (R->l == 0) {
delete R;
R = NULL;
}
}
int prefix(nod *R, char a[], int n) {
for (int i = 1; i <= n; ++i) {
if (R->next[a[i] - 'a'] == NULL) return i - 1;
R = R->next[a[i] - 'a'];
}
return n;
}
int main() {
init(R);
while ((fin >> op)) {
fin >> (a + 1);
n = strlen(a + 1);
if (op == 0) {
insert(R, a, n);
continue;
}
if (op == 1) {
erase(R, 1);
continue;
}
if (op == 2)
fout << nrAp(R, a, n) << '\n';
else
fout << prefix(R, a, n) << '\n';
}
return 0;
}