Cod sursa(job #933590)

Utilizator visanrVisan Radu visanr Data 30 martie 2013 10:48:01
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;


#define ch (*s - 'a')

struct Trie
{
    int cuv, nrfii;
    Trie *fiu[31];
    Trie()
    {
        cuv = 0;
        nrfii = 0;
        memset(fiu, 0, sizeof(fiu));
    }
};

Trie *T = new Trie;

void Insert(Trie *nod, char *s)
{
    if(*s == '\n')
    {
        nod -> cuv ++;
        return ;
    }
    if(nod -> fiu[ch] == 0)
    {
        nod -> fiu[ch] = new Trie;
        nod -> nrfii ++;
    }
    Insert(nod -> fiu[ch], s + 1);
}

int Delete(Trie *nod, char *s)
{
    if(*s == '\n')
    {
        nod -> cuv --;
    }else if(Delete(nod -> fiu[ch], s + 1))
    {
        nod -> fiu[ch] = 0;
        nod -> nrfii --;
    }
    if(nod -> nrfii == 0 && nod -> cuv == 0 && nod != T)
    {
        delete nod;
        return 1;
    }
    return 0;
}

int Count(Trie *nod, char *s)
{
    if(*s == '\n') return nod -> cuv;
    if(nod -> fiu[ch]) return Count(nod -> fiu[ch], s + 1);
    return 0;
}

int Prefix(Trie *nod, char *s, int Ans)
{
    if(*s == '\n' || nod -> fiu[ch] == 0) return Ans;
    return Prefix(nod -> fiu[ch], s + 1, Ans + 1);
}

int main()
{
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    char S[31];
    fgets(S, 31, stdin);
    while(!feof(stdin))
    {
        if(S[0] == '0') Insert(T, S + 2);
        if(S[0] == '1') Delete(T, S + 2);
        if(S[0] == '2') printf("%i\n", Count(T, S + 2));
        if(S[0] == '3') printf("%i\n", Prefix(T, S + 2, 0));
        fgets(S, 31, stdin);
    }
    return 0;
}