Pagini recente » Cod sursa (job #1428610) | Cod sursa (job #3143290) | Cod sursa (job #1826135) | Cod sursa (job #2529705) | Cod sursa (job #2070700)
#include <iostream>
#include <fstream>
using namespace std;
struct Trie {
int nr = 0, n = 0;
Trie *t[26] = { 0 };
};
Trie *T = new Trie;
void add(Trie *root, const char *w) {
if (w[0] == '\0') {
++root->nr;
return;
}
if (nullptr == root->t[w[0] - 'a']) {
root->t[w[0] - 'a'] = new Trie;
++root->n;
}
add(root->t[w[0] - 'a'], w + 1);
}
int del(Trie *root, const char *w) {
if (w[0] == '\0') {
--root->nr;
} else
if (del(root->t[w[0] - 'a'], w + 1)) {
root->t[w[0] - 'a'] = nullptr;
--root->n;
}
if (0 == root->n && 0 == root->nr && root != T) {
delete root;
return 1;
}
return 0;
}
int prefix(Trie *root, const char *w) {
if (w[0] == '\0') {
return 0;
}
if (nullptr == root->t[w[0] - 'a']) {
return 0;
}
return 1 + prefix(root->t[w[0] - 'a'], w + 1);
}
int stat(Trie *root, const char *w) {
if (w[0] == '\0') {
return root->nr;
}
if (nullptr == root->t[w[0] - 'a']) {
return 0;
}
return stat(root->t[w[0] - 'a'], w + 1);
}
int main() {
ifstream f("trie.in");
ofstream g("trie.out");
char w[21];
int i;
while (f >> i) {
f >> w;
switch (i) {
case 0:
add(T, w);
break;
case 1:
del(T, w);
break;
case 2:
g << stat(T, w) << "\n";
break;
case 3:
g << prefix(T, w) << "\n";
break;
}
}
}