Pagini recente » Cod sursa (job #3260940) | Cod sursa (job #1286584) | Cod sursa (job #97956) | Cod sursa (job #2011435) | Cod sursa (job #629928)
Cod sursa(job #629928)
#include <stdio.h>
struct dic{
char c;
int h,l;
struct dic*right,*down; };
dic*create(char w){
dic*x=new dic;
x->c=w;
x->h=0;
x->l=0;
x->right=NULL;
x->down=NULL;
return x;
}
dic*d=create('a');
dic*search(dic*step,char w){
while(step->right!=NULL&&step->c!=w)step=step->right;
if(step->c==w)return step; else return step->right=create(w);
}
void insert(char*w){
dic*step=d;
while(*w!='\0'){
step=search(step,*w);
step->h++;
if(*w!='\0')
if(step->down==NULL)step=step->down=create(*w);else step=step->down;
w++; }
step->l++;
}
int number(char*w){
dic*step=d;
while(*w!='\0'){
while(step->right!=NULL&&step->c!=*w)step=step->right;
if(step->c!=*w)return 0;
if(*w!='\0')
if(step->down==NULL)return 0;else step=step->down;
w++; }
return step->l;
}
int prefix(char*w){
dic*step=d; int max=0,x=0;
while(*w!='\0'){
while(step->right!=NULL&&step->c!=*w)step=step->right;
if(step->c!=*w)return max;else x++;
if(step->h>0)max=x;
if(*w!='\0')
if(step->down==NULL)return max;else step=step->down;
w++; }
return max;
}
void remove(char*w){
dic*step=d;
while(*w!='\0'){
while(step->c!=*w)step=step->right;
step->h--;
if(*w!='\0')step=step->down;
w++; }
step->l--;
}
int main(){
char o,w[20];
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
while(scanf("%d %s",&o,w)!=-1){
switch(o){
case 0: insert(w);break;
case 1: if(number(w)>0)remove(w);break;
case 2: printf("%d\n",number(w));break;
case 3: printf("%d\n",prefix(w));
}
}
}