Pagini recente » Cod sursa (job #829989) | Cod sursa (job #1352013) | Cod sursa (job #3224627) | Cod sursa (job #2413762) | Cod sursa (job #2300201)
#include <fstream>
#include <string>
#define ch (s[poz]-97)
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
string s;
struct Trie
{
int cuv,sons;
Trie *fii[30];
Trie()
{
cuv = sons = 0;
for(int i = 0; i < 26; i++)
fii[i] = NULL;
}
};
Trie *T;
int op;
void insert(Trie *&nod, int poz)
{
if(nod == NULL)
nod = new Trie();
if(poz == s.size())
{
nod->cuv++;
}
else
{
nod->sons++;
insert(nod->fii[ch], poz+1);
}
}
void del(Trie *&nod, int poz)
{
if(poz == s.size())
{
nod->cuv--;
}
else
{
nod->sons--;
del(nod->fii[ch], poz+1);
}
if(nod->cuv + nod->sons == 0)
delete nod,nod = NULL;
}
int aparitii(Trie *&nod, int poz)
{
if(nod == NULL)
return 0;
if(poz == s.size())
return nod->cuv;
else
return aparitii(nod->fii[ch], poz+1);
}
int prefix(Trie *&nod, int poz)
{
if(poz == s.size())
return poz;
if(nod->fii[ch] != NULL && (nod->fii[ch]->cuv || nod->fii[ch]->sons) )
return prefix(nod->fii[ch], poz+1);
return poz;
}
int main()
{
T = new Trie();
while(fin >> op)
{
fin >> s;
if(op == 0)
insert(T,0);
if(op == 1)
del(T,0);
if(op == 2)
fout<<aparitii(T,0)<<'\n';
if(op == 3)
fout<<prefix(T,0)<<'\n';
}
return 0;
}