Pagini recente » Cod sursa (job #1329760) | Cod sursa (job #1610198) | Cod sursa (job #1694495) | Cod sursa (job #2751953) | Cod sursa (job #1622425)
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int c,caz;
char w[30];
struct nod {
int prefix;
int cuvinte;
nod *v[26];
nod ()
{
for (int i=0;i<26;i++)
v[i] = NULL;
prefix = 0;
cuvinte = 0;
}
} *arb, *p, *aux;
void adauga(char s[30])
{
p = arb;
int len = strlen(s);
for (int i=0;i<len;i++)
{
c = s[i] - 'a';
if (p->v[c] == NULL)
p->v[c] = new nod();
p = p->v[c];
if (i == len-1)
p->cuvinte ++;
p->prefix ++;
}
}
void sterge(char s[30])
{
p = arb;
int len = strlen(s);
for (int i=0;i<len;i++)
{
c = s[i] - 'a';
aux = p;
p = p->v[c];
if (i == len-1)
p->cuvinte --;
p->prefix --;
if (p->prefix == 0)
{
delete(p);
aux->v[c] = NULL;
return;
}
}
}
void pfx(char s[30])
{
p = arb;
int len = strlen(s);
for (int i=0;i<len;i++)
{
c = s[i] - 'a';
if (p->v[c] == NULL)
{
fout<<i<<"\n";
return;
}
p = p->v[c];
}
}
void cuv(char s[30])
{
p = arb;
int len = strlen(s);
for (int i=0;i<len;i++)
{
c = s[i] - 'a';
if (p->v[c] == NULL)
{
fout<<"0\n";
return;
}
p = p->v[c];
}
fout<<p->cuvinte<<"\n";
}
int main()
{
arb = new nod();
while(fin>>caz)
{
fin>>w;
if (caz == 0)
adauga(w);
if (caz == 1)
sterge(w);
if (caz == 2)
cuv(w);
if (caz == 3)
pfx(w);
}
return 0;
}