Pagini recente » Cod sursa (job #1042838) | Cod sursa (job #2182703) | Cod sursa (job #2683978) | Cod sursa (job #2484848) | Cod sursa (job #2414196)
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Trie
{
int Cnt,CntKids;
Trie *kids[26];
Trie()
{
Cnt=CntKids=0;
for(int i=0;i<26;i++)
{
kids[i]=0;
}
}
};
Trie *T=new Trie;
void Insert(Trie *nod,char *s)
{
if(int(*s)==0)
{
nod->Cnt++;
}
else
{
int Value=*s-'a';
if(nod->kids[Value]==0)
{
nod->kids[Value]=new Trie;
nod->CntKids++;
}
Insert(nod->kids[Value],s+1);
}
}
bool Delete(Trie *nod,char *s)
{
if(int(*s)==0)
{
nod->Cnt--;
}
else
{
int Value=*s-'a';
if(Delete(nod->kids[Value],s+1))
{
nod->kids[Value]=0;
nod->CntKids--;
}
}
if(nod->Cnt==0 && nod->CntKids==0 && nod!=T)
{
delete nod;
return 1;
}
else
{
return 0;
}
}
int GetFrequency(Trie *nod,char *s)
{
if(int(*s)==0)
{
return nod->Cnt;
}
else
{
int Value=*s-'a';
if(nod->kids[Value]==0)
{
return 0;
}
else
{
return GetFrequency(nod->kids[Value],s+1);
}
}
}
int GetLongestPrefix(Trie *nod,char *s,int Dep)
{
int Value=*s-'a';
if(int(*s)==0 || nod->kids[Value]==0)
{
return Dep;
}
else
{
return GetLongestPrefix(nod->kids[Value],s+1,1+Dep);
}
}
int main()
{
char s[100];
while(fin.getline(s,100))
{
if(s[0]=='0') Insert(T,s+2);
if(s[0]=='1') Delete(T,s+2);
if(s[0]=='2') fout<<GetFrequency(T,s+2)<<"\n";
if(s[0]=='3') fout<<GetLongestPrefix(T,s+2,0)<<"\n";
}
}