Pagini recente » Cod sursa (job #875684) | Cod sursa (job #982588) | Cod sursa (job #536507) | Cod sursa (job #325381) | Cod sursa (job #2851323)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie
{
int cnt, nrfii;
trie *litera[30];
trie()
{
cnt = 0;
nrfii = 0;
for(int i = 0; i <= 26; i ++)
{
litera[i] = 0;
}
}
};
trie *root = new trie;
void adaugacuv(trie *nod, char *s)
{
char ch = *s;
if(ch < 'a' || ch > 'z')
{
nod->cnt++;
return ;
}
else
{
ch -= 'a';
if(nod->litera[ch] == 0)
{
nod->litera[ch] = new trie;
nod->nrfii++;
}
adaugacuv(nod->litera[ch], s + 1);
}
}
int cntWords(trie *nod, char *s)
{
char ch = *s;
if(ch < 'a' || ch > 'z')
{
return nod->cnt;
}
ch -= 'a';
if(nod->litera[ch])
{
return cntWords(nod->litera[ch], s + 1);
}
return 0;
}
bool stergecuv(trie *nod, char *s)
{
char ch = *s;
if(ch < 'a' || ch > 'z')
{
nod->cnt--;
}
else
{
ch -= 'a';
if(stergecuv(nod->litera[ch], s + 1) == 1)
{
nod->litera[ch] = 0;
nod->nrfii--;
}
}
if(nod->cnt == 0 && nod->nrfii == 0 && nod != root)
{
delete nod;
return 1;
}
return 0;
}
int cntPref(trie *nod, char *s, int ans)
{
char ch = *s;
if(ch > 'z' || ch < 'a')
{
return ans;
}
ch -= 'a';
if(nod->litera[ch] == 0)
{
return ans;
}
else
{
return cntPref(nod->litera[ch], s + 1, ans + 1);
}
}
int main()
{
int operatie;
while(fin >> operatie)
{
char s[50];
fin >> s;
if(operatie == 0)
{
adaugacuv(root, s);
}
if(operatie == 1)
{
stergecuv(root, s);
}
if(operatie == 2)
{
fout << cntWords(root, s) << '\n';
}
if(operatie == 3)
{
fout << cntPref(root, s, 0) << '\n';
}
}
return 0;
}