Cod sursa(job #1625327)

Utilizator FullP0werMihalache Andrei FullP0wer Data 2 martie 2016 18:12:11
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <cstdio>
#include <algorithm>
#include <cstring>
#define x (*c-'a')
using namespace std;
char s[30];
int X;
struct Trie{
   Trie* next[26];
   int a, b;
   Trie(){
    a = 0;
    b = 0;
    memset( next, 0, sizeof( next ) );
   }
};
Trie *T = new Trie;
void Insert(Trie *nod, char* c){
    if(*c == '\n'){
        nod->a++; return;
    }
    if(!(nod->next[x])){
        nod->next[x] = new Trie;
        nod->b++;
    }
    Insert(nod->next[x], c+1);
}
int Delete(Trie* nod, char* c){
    if(*c == '\n'){
        nod->a--;
    }
    else{
        if( Delete(nod->next[x], c+1) ){
            nod->next[x] = 0;
            nod->b--;
        }
    }
    if(nod->a == 0 && nod->b == 0 && nod != T){
        delete nod; return 1;
    }
    return 0;
}
int NR(Trie* nod, char* c){
    if(*c == '\n'){
        return nod->a;
    }
    if(nod->next[x]) return NR(nod->next[x], c+1);
    return 0;
}
int Pref(Trie* nod, char* c, int nr){
    if(*c == '\n' || nod->next[x] == 0) return nr;
    return Pref(nod->next[x], c+1, nr+1);
}
int main(){
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    scanf("%d", &X);
    fgets(s, 21, stdin);
    while (!feof(stdin)){
        if(!X) Insert(T, s+1);
        if(X == 1) Delete(T, s+1);
        if(X == 2) printf("%d\n", NR(T, s+1));
        if(X == 3) printf("%d\n", Pref(T, s+1, 0));
        scanf("%d", &X);
        fgets(s, 21, stdin);
    }
    return 0;
}