Pagini recente » Cod sursa (job #3316702) | Cod sursa (job #2833609) | Cod sursa (job #177403) | Cod sursa (job #2011532) | Cod sursa (job #3315787)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
const int NMAX=27;
class Node{
public:
Node *sons[NMAX];
int freq;
int ending;
Node()
{
freq=0;
ending=0;
for(int i=0;i<NMAX;i++)
sons[i]=NULL;
}
};
void add(Node *&node,string s,int poz)
{
if(poz==s.length())
return ;
if(node->sons[s[poz]-'a']==NULL)
node->sons[s[poz]-'a']=new Node();
node->sons[s[poz]-'a']->freq++;
if(poz==s.length()-1)
node->sons[s[poz]-'a']->ending++;
add(node->sons[s[poz]-'a'],s,poz+1);
}
void rem(Node *&node,string s,int poz)
{
if(poz==s.length())
return ;
if(node->sons[s[poz]-'a']==NULL)
return ;
node->sons[s[poz]-'a']->freq--;
if(poz==s.length()-1)
node->sons[s[poz]-'a']->ending--;
rem(node->sons[s[poz]-'a'],s,poz+1);
}
int get_freq(Node *&node,string &s,int poz)
{
if(poz==s.length())
return 0;
if(node->sons[s[poz]-'a']==NULL)
return 0;
if(poz==s.length()-1)
return node->sons[s[poz]-'a']->ending;
return get_freq(node->sons[s[poz]-'a'],s,poz+1);
}
int lcp(Node *&node,string s,int poz,int lvl)
{
if(poz==s.length())
return lvl;
if(node->sons[s[poz]-'a']==NULL)
return lvl;
if(node->sons[s[poz]-'a']->freq==0)
return lvl;
return lcp(node->sons[s[poz]-'a'],s,poz+1,lvl+1);
}
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
Node *node=new Node();
int type;
string s;
while(fin>>type>>s)
{
if(type==0)
add(node,s,0);
else if(type==1)
rem(node,s,0);
else if(type==2)
fout<<get_freq(node,s,0)<<"\n";
else
fout<<lcp(node,s,0,0)<<"\n";
}
return 0;
}