Cod sursa(job #629927)

Utilizator Luncasu_VictorVictor Luncasu Luncasu_Victor Data 4 noiembrie 2011 10:44:45
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#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("test.in","r",stdin);
    freopen("test.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));
            }
        }
}