Pagini recente » Cod sursa (job #1365948) | Cod sursa (job #2903729) | Cod sursa (job #2818912) | Cod sursa (job #2815809) | Cod sursa (job #2553658)
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct Trie {
Trie *copii[26];
int con;
Trie() {
for (int i = 0; i < 26; ++i)
copii[i] = nullptr;
con = 0;
}
};
string str = "";
int l_str = 0;
Trie *p = new Trie();
void inserare(Trie *nod, int index) {
if (index == l_str) {
++nod->con;
return;
}
int temp = str[index] - 'a';
if (nod->copii[temp] == nullptr)
nod->copii[temp] = new Trie();
inserare(nod->copii[temp], index + 1);
}
void sterge(Trie *node, int index) {
if (index == l_str) {
--node->con;
return;
}
int temp = str[index] - 'a';
sterge(node->copii[temp], index + 1);
if (node->copii[temp]->con == 0 && index == l_str - 1) {
delete node->copii[temp];
node->copii[temp] = nullptr;
}
}
int afisare_nr(Trie *nod, int index) {
if (index == l_str)
return nod->con;
int temp = str[index] - 'a';
if (nod->copii[temp] == nullptr)
return 0;
return afisare_nr(nod->copii[temp], index + 1);
}
int afisare_lungime(Trie *nod, int index) {
if (index == l_str)
return l_str;
int temp = str[index] - 'a';
if (nod->copii[temp] == nullptr)
return index;
return afisare_lungime(nod->copii[temp], index + 1);
}
int main() {
int comanda = 0;
Trie radacina = *new Trie();
while (f >> comanda >> str) {
l_str = str.length();
switch (comanda) {
case 0:
inserare(&radacina,0);
break;
case 1:
sterge(&radacina,0);
break;
case 2:
g<<afisare_nr(&radacina,0)<<endl;
break;
case 3:
g<<afisare_lungime(&radacina,0)<<endl;
break;
}
}
return 0;
}