Pagini recente » Cod sursa (job #2770773) | Cod sursa (job #784715) | Cod sursa (job #1168519) | Cod sursa (job #2388469) | Cod sursa (job #2848473)
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
struct trie
{
int cnt,nrfii;
vector<trie*> fii;
trie()
{
cnt=nrfii=0;
fii.resize(26);
fii.assign(26,NULL);
}
};
trie* T=new trie;
string w;
int op;
void ins(trie* nod,string::iterator s);
bool del(trie* nod,string::iterator s);
int app(trie* nod,string::iterator s);
int len(trie* nod,string::iterator s);
int main()
{
while(fin>>op>>w)
{
if(op==0)
ins(T,w.begin());
if(op==1)
del(T,w.begin());
if(op==2)
fout<<app(T,w.begin())<<'\n';
if(op==3)
fout<<len(T,w.begin())<<'\n';
}
fin.close();
fout.close();
return 0;
}
void ins(trie* nod,string::iterator s)
{
int ch=*s-'a';
if(s==w.end())
{
nod->cnt++;
return;
}
if(nod->fii[ch]==NULL)
{
nod->fii[ch]=new trie;
nod->nrfii++;
}
ins(nod->fii[ch],s+1);
return;
}
bool del(trie* nod,string::iterator s)
{
int ch=*s-'a';
if(s==w.end())
nod->cnt--;
else
if(del(nod->fii[ch],s+1))
{
nod->fii[ch]=NULL;
nod->nrfii--;
}
if(nod->nrfii==0&&nod->cnt==0&&nod!=T)
{
delete nod;
return true;
}
return false;
}
int app(trie* nod,string::iterator s)
{
int ch=*s-'a';
if(s==w.end())
return nod->cnt;
if(nod->fii[ch]!=NULL)
return app(nod->fii[ch],s+1);
return 0;
}
int len(trie* nod,string::iterator s)
{
if(s==w.end())
return w.size();
int ch=*s-'a';
if(nod->fii[ch]!=NULL)
return len(nod->fii[ch],s+1);
return s-w.begin();
}