Cod sursa(job #889708)

Utilizator Theorytheo .c Theory Data 24 februarie 2013 17:46:15
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include<cstdio>
#include<cstring>

#define CH (*s - 'a')

using namespace std;

struct Nod{

    Nod *Son[26];
    int cnt, NumberSons;

    Nod(){
        memset(Son, 0, sizeof(Son)); cnt = 0; NumberSons = 0;}
};

Nod *T = new Nod;

void Insert(Nod *X, char *s){
    if(*s == '\n' || *s == '\0'){
         X -> cnt++; return ;
    }

    if( X -> Son[CH] == 0){
        X -> Son[CH] = new Nod;
        X -> NumberSons++;
    }

    Insert(X -> Son[CH], s + 1);
}


int Delete(Nod *X, char *s){

    if(*s == '\n' || *s == '\0')
        X -> cnt--;
        else if(Delete(X -> Son[CH], s + 1)){
            X -> Son[CH] = 0;
            X -> NumberSons--;
        }
    if(X -> cnt == 0 && X -> NumberSons == 0 && X != T){
        delete X; return 1;
    }
    return 0;
}

int Query(Nod *X, char *s){

    if(*s == '\n') return  X -> cnt;
    if(X -> Son[CH])
        return Query(X -> Son[CH] , s + 1);
    return 0;
}


int Prefix(Nod *X, char *s, int Lung){

    if(*s == '\n' || X -> Son[CH] == 0) return Lung;

    return Prefix(X -> Son[CH], s + 1, Lung + 1);
}


int main(){

    char Line[32];

    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    fgets(Line, 32, stdin);

    while(!feof(stdin)){

        switch(Line[0]){
            case '0': Insert(T,Line + 2); break;
            case '1': Delete(T, Line + 2); break;
            case '2':  printf("%d\n" , Query(T, Line + 2)); break;
            case '3': printf("%d\n", Prefix(T, Line + 2, 0)); break;
        }
        fgets(Line, 32, stdin);
    }

    return 0;
}