Pagini recente » Cod sursa (job #1690197) | Cod sursa (job #1690418) | Cod sursa (job #2201709) | Cod sursa (job #1424320) | Cod sursa (job #2753030)
#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 *t1 = t;
int i = -1;
int n = strlen(cuvant);
while(t1)
{
i++;
t1 = t1->fii[cuvant[i] - 'a'];
}
return i;
}
void sterge2(trie *t1, char *cuvant, int i, int &stop)
{
int n = strlen(cuvant);
if(stop == 0)
{
if(i <= n - 2)
{
sterge2(t1->fii[cuvant[i + 1] - 'a'], cuvant, i + 1, stop);
if(stop == 0)
{
t1->nr_fii--;
delete t1->fii[cuvant[i + 1] - 'a'];
t1->fii[cuvant[i + 1] - 'a'] = NULL;
if(t1->nr_fii >= 1)
stop = 1;
}
}
else
{
if(t1->nr_ap_cuvant > 1 || t1->nr_fii > 0)
{
t1->nr_ap_cuvant--;
stop = 1;
}
}
}
}
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')
{
fout << lung_prefix(sir + 2) << "\n";
}
else
{
if(sir[0] == '1')
{
int stop = 0;
trie *t1 = t;
sterge2(t1, sir + 2, -1, stop);
}
}
}
}
}
return 0;
}