Pagini recente » Cod sursa (job #1544732) | Cod sursa (job #2961056)
#include<bits/stdc++.h>
using namespace std;
struct Trie
{
int cnt = 0;
int howMany = 0;
Trie* sons[26];
Trie()
{
for(int i=0;i<26;i++)
sons[i] = NULL;
}
};
string str;
Trie* root = new Trie();
void Insert(string &w,Trie* node,int pos)
{
(*node).howMany++;
if(pos==w.size())
{
(*node).cnt++;
return;
//node->cnt++;
}
//'a' - 0, 'b' - 1,...
if(node->sons[w[pos]-'a']==NULL)
{
node->sons[w[pos]-'a'] = new Trie();
}
Insert(w,node->sons[w[pos]-'a'],pos+1);
}
void Delete(string &w,Trie* node,int pos)
{
(*node).howMany--;
if(pos==w.size())
{
(*node).cnt--;
return;
//node->cnt++;
}
//'a' - 0, 'b' - 1,...
if(node->sons[w[pos]-'a']==NULL)
return;
Delete(w,node->sons[w[pos]-'a'],pos+1);
}
int Query1(string &w,Trie* node,int pos)
{
if(pos==w.size())
{
return (*node).cnt;
}
//'a' - 0, 'b' - 1,...
if(node->sons[w[pos]-'a']==NULL)
return 0;
return Query1(w,node->sons[w[pos]-'a'],pos+1);
}
int Query2(string &w,Trie* node,int pos)
{
if(pos==w.size())
{
return w.size();
}
//'a' - 0, 'b' - 1,...
if(node->sons[w[pos]-'a']==NULL || node->sons[w[pos]-'a']->howMany == 0)
return pos;
//[0..pos-1]
return Query2(w,node->sons[w[pos]-'a'],pos+1);
}
int main()
{
ifstream fin("trie.in");
ofstream fout("trie.out");
//op str
int op;
while(fin>>op)
{
fin>>str;
if(op==0)
Insert(str,root,0);
else
if(op==1)
Delete(str,root,0);
else
if(op==2)
fout<<Query1(str,root,0)<<'\n';
else
if(op==3)
fout<<Query2(str,root,0)<<'\n';
//break;
}
return 0;
}