Pagini recente » Cod sursa (job #2161080) | Cod sursa (job #2231820) | Cod sursa (job #1537509) | Cod sursa (job #1631923) | Cod sursa (job #2763762)
#include <fstream>
using namespace std;
struct Trie{
int nr, nrcuv;
Trie *lit[26];
Trie() {
nrcuv = nr = 0;
for (int i = 0; i <= 25; 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] == NULL) {
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->lit[l] = NULL;
nod->nr--;
}
}
if (nod->nr == 0 && nod->nrcuv == 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] != NULL)
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] != NULL)
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;
}