Cod sursa(job #1829366)

Utilizator antanaAntonia Boca antana Data 14 decembrie 2016 20:49:43
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <cstdio>
#include <cstring>

#define MAXN 30
#define MAXC 26
#define code(x) (x-'a')

struct trie{
    int nr, subtrees;
    trie *son[MAXC];

    trie(){
        nr = subtrees = 0;
        memset(son, 0, sizeof son);
    }
}*root;

char s[MAXN];

void add_trie(trie *aux, char *s)
{
    if(*s == NULL)
    {
        aux->nr++;
        return;
    }

    if(aux->son[code(*s)] == NULL)
    {
        aux->son[code(*s)] = new trie;
        aux->subtrees++;
    }

    add_trie(aux->son[code(*s)], s+1);
}

bool delete_trie(trie *aux, char *s)
{
    if(*s == NULL)
        aux->nr--;

    else
    {
        if(delete_trie(aux->son[code(*s)], s+1))
        {
            aux->son[code(*s)] = NULL;
            aux->subtrees--;
        }
    }

    if(aux->subtrees == 0 && aux->nr == 0 && aux != root)
    {
        delete aux;
        return 1;
    }
    return 0;
}

int find_trie(trie *aux, char *s)
{
    if(*s == NULL)
        return aux->nr;

    if(aux->son[code(*s)] != 0)
        return find_trie(aux->son[code(*s)], s+1);

    return 0;
}

int longest_prefix(trie *aux, char *s)
{
    if(*s == NULL || aux->son[code(*s)] == NULL)
        return 0;

    return longest_prefix(aux->son[code(*s)], s+1) + 1;
}

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

    int q, f;

    root = new trie;

    gets(s);

    while(!feof(stdin))
    {
        q = s[0] - '0';

        strcpy(s, s+2);

        if(q == 0) add_trie(root, s);
        if(q == 1) f = delete_trie(root, s);
        if(q == 2) printf("%d\n", find_trie(root, s));
        if(q == 3) printf("%d\n", longest_prefix(root, s));

        gets(s);
    }

    return 0;
}