Pagini recente » Cod sursa (job #262694) | Cod sursa (job #3000992) | Cod sursa (job #2726240) | Cod sursa (job #2174977) | Cod sursa (job #423268)
Cod sursa(job #423268)
#include <cstdio>
#include <cstring>
#define ALF 27
struct trie{
int key,nrChild;
trie* child[ALF];
trie(){
key=nrChild=0;
memset(child,0,sizeof(child));
}
};
FILE* fin=fopen("trie.in","r");
FILE* fout=fopen("trie.out","w");
trie root;
char buf[100];
void add(trie* ptr,char* c){
while(*c!='\n'){
if(ptr->child[*c-'a']==0){
ptr->child[*c-'a']=new trie(),ptr->nrChild++;
}
ptr=ptr->child[*c-'a'],c++;
}
ptr->key++;
}
int del(trie* ptr,char* c){
if(*c=='\n'){
ptr->key--;
}else if(del(ptr->child[*c-'a'],c+1)){
ptr->child[*c-'a']=0;
ptr->nrChild--;
}
if(ptr->key==0&&ptr->nrChild==0&&ptr!=&root){
delete ptr;
return 1;
}
return 0;
}
int num(trie* ptr,char* c){
while(*c!='\n'){
if(ptr->child[*c-'a']==0){
return 0;
}
ptr=ptr->child[*c-'a'],c++;
}
return ptr->key;
}
int lcp(trie* ptr,char* c){
int nr=0;
while(*c!='\n'&&ptr->child[*c-'a']){
ptr=ptr->child[*c-'a'],nr++,c++;
}
return nr;
}
int main(){
int op,len;
while(fgets(buf,sizeof(buf),fin)){
switch(buf[0]){
case '0':
add(&root,buf+2);
break;
case '1':
del(&root,buf+2);
break;
case '2':
fprintf(fout,"%d\n",num(&root,buf+2));
break;
case '3':
fprintf(fout,"%d\n",lcp(&root,buf+2));
break;
}
}
fclose(fin);
fclose(fout);
return 0;
}