Pagini recente » Cod sursa (job #2222388) | Cod sursa (job #2388912) | Cod sursa (job #3276628) | Cod sursa (job #1876933) | Cod sursa (job #3166418)
#include <bits/stdc++.h>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct nod{
nod *fiu[26]; /// 26 pointeri - fiecare reprezentand cate o litera
int nr_fii;
int nr_ap;
nod() { /// constructor - aceste instructiuni se executa la crearea unui nod nou
fill(fiu, fiu+26, nullptr); /// sau cu un for (sa punem nullptr sau 0 in fiu[0->25])
nr_fii = 0;
nr_ap = 0;
}
};
nod *root = new nod; /// radacina retine defapt ""
string w;
int op;
bool ok=0;
int max_pref;
void adds(nod *x, int pos) {
if (pos==w.size()) {
x->nr_ap++;
return;
}
/// w[pos] = a pos-a litera din cuvant (cea la care trebuie sa mergem)
/// fiu[w[pos]-'a'] = pointer-ul corespunzator catre acea litera
if (x->fiu[w[pos]-'a'] == nullptr) {
x->fiu[w[pos]-'a'] = new nod;
x->nr_fii++;
}
adds(x->fiu[w[pos]-'a'], pos+1);
}
bool memory_delete(nod *x) {
if (x->nr_ap==0 && x->nr_fii==0 && x!=root) {
delete x;
return 1; /// am sters nodul
}
return 0; /// nu am sters nodul din memorie
}
void deletes(nod *x, int pos) {
if (pos==w.size()) {
x->nr_ap--;
ok = memory_delete(x);
return;
}
deletes(x->fiu[w[pos]-'a'], pos+1);
if (ok == 1) {
x->fiu[w[pos]-'a'] = nullptr;
x->nr_fii--;
}
ok = memory_delete(x);
}
int appears(nod *x, int pos) {
if (pos==w.size()) return x->nr_ap;
else if (x->fiu[w[pos]-'a'] != nullptr) {
return appears(x->fiu[w[pos]-'a'], pos+1);
}
return 0;
}
int common_prefix(nod *x, int pos) {
if (x->fiu[w[pos]-'a'] == nullptr || pos == w.size()) {
return pos;
}
return common_prefix(x->fiu[w[pos]-'a'], pos+1);
}
int main()
{
while (f >> op) {
f >> w;
if (op==0) {
adds(root, 0);
}
else if (op==1) {
deletes(root, 0);
}
else if (op==2) {
g << appears(root, 0) << '\n';
}
else {
g << common_prefix(root, 0) << '\n';
}
}
return 0;
}