Pagini recente » Cod sursa (job #624776) | Istoria paginii runda/pogo.danseaza/clasament | Cod sursa (job #1529836) | Cod sursa (job #3124122) | Cod sursa (job #2702596)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct nod{
nod *fiu[26];
int end_of;
int sons;
nod()
{
memset(fiu,0,sizeof(fiu));
end_of=0;
sons=0;
}
};
nod* root=new nod;
int c;
string word;
void add(nod *parent,int pos)
{
if(pos==word.size())
{
parent->end_of++;
return;
}
if(parent->fiu[word[pos]-'a']==0)
{
parent->fiu[word[pos]-'a']=new nod;
parent->sons++;
}
add(parent->fiu[word[pos]-'a'],pos+1);
}
bool pop(nod *parent,int pos)
{
if(pos==word.size())
parent->end_of--;
else
if(pop(parent->fiu[word[pos]-'a'],pos+1))
{
parent->fiu[word[pos]-'a']=0;
parent->sons--;
}
if(parent->end_of==0 && parent->sons==0 && parent!=root)
{
delete parent;
return true;
}
return false;
}
int count_words(nod *parent,int pos)
{
if(pos==word.size())
return parent->end_of;
if(parent->fiu[word[pos]-'a']==0)
return 0;
return count_words(parent->fiu[word[pos]-'a'],pos+1);
}
int common_prefix(nod *parent,int pos)
{
if(pos==word.size())
return pos;
if(parent->fiu[word[pos]-'a']==0)
return pos;
return common_prefix(parent->fiu[word[pos]-'a'],pos+1);
}
int main()
{
while(fin>>c)
{
fin>>word;
if(c==0)
{
add(root,0);
continue;
}
if(c==1)
{
pop(root,0);
continue;
}
if(c==2)
{
fout<<count_words(root,0)<<"\n";
continue;
}
fout<<common_prefix(root,0)<<"\n";
}
return 0;
}