Cod sursa(job #959789)

Utilizator cousin.batmanVaru Batman cousin.batman Data 8 iunie 2013 18:41:17
Problema Trie Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.8 kb
#include<string.h>
#include<stdio.h>
#include<stdlib.h>

typedef struct node_s { 
    int pref;
    int end;
    struct node_s *next[28];
} node;

node HEAD;

void add(node *p, char *word){
    if(p==NULL) return;
    if(*word==0){
        p->end++;
        p->pref++;
        return;
    }
    if(p->next[*word]==NULL)
        p->next[*word] = (node*) calloc(1, sizeof(node));
    add(p->next[*word], word+1);
}

void rem(node *p, char *word){
    if(p==NULL) return;
    if(*word==0)
        p->end--;
    else {
        rem(p->next[*word], word+1);
        if(p->next[*word]->pref==0){
            free(p->next[*word]);
            p->next[*word] = NULL;
        }
    }    
    p->pref--;
}

int get_count(node *p, char *word){
    if(p==NULL) return -1;
    if(*word==0) return p->end;
    return get_count(p->next[*word], word+1);
}

int max_pref(node *p, char *word){
    if(p==NULL) return -1;
    if(*word==0) return 0;
    return 1+max_pref(p->next[*word], word+1);
}

int main(){
    char line[32];
    int i, res;

    freopen("trie.in", "rt", stdin);
    freopen("trie.out", "wt", stdout);

    fgets(line, 32, stdin);
    while(!feof(stdin)){
        if(line[strlen(line)-1]=='\n')
            line[strlen(line)-1] = 0;

        for(i=2; line[i]!=0; ++i)
            line[i]-='a'-1;

        switch(line[0]){
            case '0': add(&HEAD, line+2); res=-1; break;
            case '1': rem(&HEAD, line+2); res=-1; break;
            case '2': res = get_count(&HEAD, line+2); break;
            case '3': res = max_pref(&HEAD, line+2); break;
        }
        if(res!=-1){
            /*for(i=2; line[i]!=0; ++i)
                line[i]+='a'-1;
            printf("%s => %d\n", line, res);*/
            printf("%d\n", res);
        }

        fgets(line, 32, stdin);
    }


    fclose(stdin);
    fclose(stdout);
    return 0;
}