Pagini recente » Cod sursa (job #1108090) | Cod sursa (job #576798) | Cod sursa (job #3233639) | Cod sursa (job #2734540) | Cod sursa (job #2753056)
#include <bits/stdc++.h>
#define L_ALF 26
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie
{
trie *fii[L_ALF];
int nr_ap_cuvant, nr_fii;
};
trie *t;
trie* aloca_mem_nod()
{
trie *nod_nou = new trie;
nod_nou->nr_fii = 0;
nod_nou->nr_ap_cuvant = 0;
for(int i = 0; i < L_ALF; i++)
{
nod_nou->fii[i] = NULL;
}
return nod_nou;
}
void adauga(char *s)
{
int n = strlen(s);
int indice_litera;
trie *t1 = t;
for(int i = 0; i < n - 1; i++) // merg pana la penultima litera
{
indice_litera = s[i] - 'a';
if(!t1->fii[indice_litera])
{
t1->fii[indice_litera] = aloca_mem_nod();
t1->nr_fii++;
}
t1 = t1->fii[indice_litera];
}
indice_litera = s[n - 1] - 'a'; // ultima litera incheie cuvantul, e speciala ptr ca aici nr_ap_cuvant++
if(!t1->fii[indice_litera])
{
t1->fii[indice_litera] = aloca_mem_nod();
t1->nr_fii++;
}
t1->fii[indice_litera]->nr_ap_cuvant++;
}
int nr_aparitii(char *cuvant)
{
trie *t1 = t;
int n = strlen(cuvant);
int i = 0;
while(i < n && t1->fii[cuvant[i] - 'a'])
{
t1 = t1->fii[cuvant[i] - 'a'];
i++;
}
if(i == n)
return t1->nr_ap_cuvant;
else
return 0;
}
int lung_prefix(char *cuvant, trie *&nod)
{
trie *t1 = t;
int i = -1;
int n = strlen(cuvant);
while(t1)
{
i++;
if(i == n)
break;
nod = t1;
t1 = t1->fii[cuvant[i] - 'a'];
}
return i;
}
void sterge1(trie *nod, char *cuvant, int i)
{
if(i < strlen(cuvant) && nod->fii[cuvant[i] - 'a'])
{
sterge1(nod->fii[cuvant[i] - 'a'], cuvant, i + 1);
trie *p = nod->fii[cuvant[i] - 'a'];
nod->fii[cuvant[i] - 'a'] = NULL;
delete p;
}
}
void sterge2(char *cuvant)
{
int n = strlen(cuvant), lungime_prefix;
int i = -1, k = 0;
trie *t2 = t;
trie *nod_prefix = t;
while(1)
{
if(t2->nr_fii > 0)
{
nod_prefix = t2;
k = i + 1;
}
i++;
if(i == n)
break;
t2 = t2->fii[cuvant[i] - 'a'];
}
if(nod_prefix == t2)
{
(t2->nr_ap_cuvant)--;
}
else
{
sterge1(nod_prefix, cuvant, k);
}
}
int main()
{
char sir[32];
t = aloca_mem_nod();
while(fin.getline(sir, 32))
{
if(sir[0] == '0')
{
adauga(sir + 2);
}
else
{
if(sir[0] == '2')
{
fout << nr_aparitii(sir + 2) << "\n";
}
else
{
if(sir[0] == '3')
{
trie *nod = NULL;
fout << lung_prefix(sir + 2, nod) << "\n";
}
else
{
if(sir[0] == '1')
{
int stop = 0;
sterge2(sir + 2);
}
}
}
}
}
return 0;
}