Pagini recente » Cod sursa (job #1659977) | Cod sursa (job #1453461) | Cod sursa (job #2369500) | Istoria paginii runda/kl | Cod sursa (job #2763768)
#include <fstream>
using namespace std;
struct Trie {
int nrcuv, nr;
Trie* lit[26];
Trie() {
nrcuv = nr = 0;
for (int i = 0; i < 26; i++)
lit[i] = 0;
}
};
Trie* root = new Trie();
void insert(Trie* nod, char s[]) {
if (*s == 0)
nod->nrcuv++;
else {
int l = *s - 'a';
if (nod->lit[l] == 0) {
nod->lit[l] = new Trie();
nod->nr++;
}
insert(nod->lit[l], s + 1);
}
}
bool Delete(Trie* nod, char s[]) {
if (*s == 0)
nod->nrcuv--;
else {
int l = *s - 'a';
if (Delete(nod->lit[l], s + 1)) {
nod->nr--;
nod->lit[l] = 0;
}
}
if (nod->nrcuv == 0 && nod->nr == 0 && nod != root) {
delete nod;
return 1;
}
return 0;
}
int search(Trie *nod, char s[]) {
if (*s == 0)
return nod->nrcuv;
else {
int l = *s - 'a';
if (nod->lit[l] != 0)
return search(nod->lit[l], s + 1);
}
return 0;
}
int clpc(Trie *nod, char s[], int nr) {
if (*s == 0)
return nr;
else {
int l = *s - 'a';
if (nod->lit[l] != 0)
return clpc(nod->lit[l], s + 1, nr + 1);
}
return nr;
}
void solve() {
int op;
char s[21];
ifstream f("trie.in");
ofstream g("trie.out");
while (f >> op >> s) {
if (op == 0)
insert(root, s);
else if (op == 1)
Delete(root, s);
else if (op == 2)
g << search(root, s) << '\n';
else g << clpc(root, s, 0) << '\n';
}
f.close();
g.close();
}
int main() {
solve();
return 0;
}