Pagini recente » Monitorul de evaluare | Cod sursa (job #3349968)
#include<fstream>
#include<iostream>
#include<vector>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int nrLit='z'-'a'+1;
struct node{
int cnt;//cate cuvinte "trec"
int finish;//cate cuvinte se termina pe pozitia crt
vector<node*>lit;
node(){
cnt=0;
finish=0;
lit.resize(nrLit,nullptr);
};
};
node* addWord(string &cuv,int poz,node *crt){
if(crt==nullptr){
crt=new node();
}
crt->cnt++;
if(poz==cuv.size()){
crt->finish++;
return crt;
}
crt->lit[cuv[poz]-'a'] =addWord(cuv,poz+1,crt->lit[cuv[poz]-'a']);
return crt;
}
int countWord(string &cuv,int poz,node *crt){
if(crt==nullptr){
return 0;
}
if(poz==cuv.size()){
return crt->finish;
}
return countWord(cuv,poz+1,crt->lit[cuv[poz]-'a']);
}
void eraseWord(string &cuv,int poz,node *crt,bool &checkErase){//checkErase ne spune daca cuvantul cuv se afla in lista sau nu
if(crt==nullptr){
checkErase=false;
return ;
}
if(poz==cuv.size()){
checkErase=true;
crt->finish--;
crt->cnt--;
return;
}
eraseWord(cuv,poz+1,crt->lit[cuv[poz]-'a'],checkErase);
if(checkErase){//inseamna ca exista cuvantul in trie
crt->cnt--;
}
}
int countPrefix(string &cuv,int poz,node *crt){
if(crt==nullptr|| crt->cnt==0){
return -1;
}
if(poz==cuv.size()){
return 0;
}
return 1+countPrefix(cuv,poz+1,crt->lit[cuv[poz]-'a']);
}
int main(){
int cer;
string s;
node *root=new node();
root->cnt=-1;
while(fin>>cer>>s){
if(cer==0){
addWord(s,0,root);
}else if(cer==1){
bool erased=false;
eraseWord(s,0,root,erased);
}else if(cer==2){
fout<<countWord(s,0,root)<<"\n";
}else if(cer==3){
fout<<countPrefix(s,0,root)<<"\n";
}
}
return 0;
}