Pagini recente » Cod sursa (job #1414091) | Cod sursa (job #2511071) | Cod sursa (job #1787755) | Cod sursa (job #862810) | Cod sursa (job #1960977)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct _nod{
int nrSons=0, nrEnd=0;
_nod *SONS[26]= {}; //sau map
};
_nod *root=new _nod;
void add(_nod *nod, string str){
nod->nrSons++;
for(auto c : str){
if(nod->SONS[c-'a']==NULL)
nod->SONS[c-'a']=new _nod;
nod=nod->SONS[c-'a'];
nod->nrSons++;
}
nod->nrEnd++;
}
void del(_nod *nod, string str){
nod->nrSons--;
for(auto c : str){
nod=nod->SONS[c-'a'];
nod->nrSons--;
}
nod->nrEnd--;
}
int aparitii(_nod *nod, string str){
for(auto c : str){
if(nod->SONS[c-'a']==0)
return 0;
nod=nod->SONS[c-'a'];
}
return nod->nrEnd;
}
int longest_common_prefix(_nod *nod, string str){
int lcp=0;
for(auto c : str){
if(nod->SONS[c-'a']==0 || nod->SONS[c-'a']->nrSons==0)
break;
lcp++;
nod=nod->SONS[c-'a'];
}
return lcp;
}
void queries(){
int x;
string s;
while(in>>x){
in>>s;
if(x==0)
add(root,s);
else if(x==1)
del(root,s);
else if(x==2)
out<<aparitii(root,s)<<"\n";
else if(x==3)
out<<longest_common_prefix(root,s)<<"\n";
}
}
int main(){
queries();
return 0;
}