Pagini recente » Cod sursa (job #1948138) | Cod sursa (job #785025) | Cod sursa (job #732324) | Cod sursa (job #1637744) | Cod sursa (job #2080871)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream f ("trie.in");
ofstream g ("trie.out");
const int NMAX = 20;
char s[NMAX + 2];
class Trie {
public:
int cuvinte;
int aparitii;
Trie *fii[26];
Trie() {
aparitii = 0;
cuvinte = 0;
for (int i = 0; i < 26; i++)
fii[i] = NULL;
}
};
Trie *t;
Trie *adauga(char *s, Trie *t) {
if (t == NULL) t = new Trie();
t->aparitii++;
if (s[0] == 0) {
t->cuvinte++;
return t;
}
t->fii[s[0] - 'a'] = adauga(s + 1, t->fii[s[0] - 'a']);
return t;
}
Trie *sterge(char *s, Trie *t) {
if (t == NULL) return NULL;
t->aparitii--;
if (s[0] == 0) {
t->cuvinte--;
}
else {
t->fii[s[0] - 'a'] = sterge(s + 1, t->fii[s[0] - 'a']);
}
if (t->aparitii == 0) {
delete t;
return NULL;
}
return t;
}
int nr_aparitii(char *s, Trie *t) {
if (t == NULL) return 0;
if (s[0] == 0) return t->cuvinte;
return nr_aparitii(s + 1, t->fii[s[0] - 'a']);
}
int prefix(char *s, Trie *t) {
if (t == NULL) return -1;
if (s[0] == 0) return 0;
return 1 + prefix(s + 1, t->fii[s[0] - 'a']);
}
void rezolva() {
int op;
while (f >> op >> s) {
if (op == 0) t = adauga(s, t);
if (op == 1) t = sterge(s, t);
if (op == 2) g << nr_aparitii(s, t) << '\n';
if (op == 3) g << prefix(s, t) << '\n';;
}
}
int main() {
rezolva();
}