Cod sursa(job #237735)

Utilizator DastasIonescu Vlad Dastas Data 30 decembrie 2008 16:36:31
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <cstdio>
#include <iostream>

const int maxa = 26;

FILE *in = fopen("trie.in","r"), *out = fopen("trie.out","w");

struct node
{
    int answ, nrs;

    node *next[maxa];

    node()
    {
        answ = nrs = 0;
        memset(next, 0, sizeof(next));
    }
};

void insert(node *&t, char *word)
{
    if ( *word == '\0' )
    {
        ++t->answ;
        return;
    }

    int val = *word - 'a';
    if ( t->next[val] == 0 )
    {
        t->next[val] = new node;
        ++t->nrs;
    }

    insert(t->next[val], word+1);
}

int del(node *main, node *&t, char *word)
{
    int val = *word - 'a';
    if ( *word == '\0' )
        --t->answ;
    else if ( del(main, t->next[val], word+1) )
    {
        t->next[val] = 0;
        --t->nrs;
    }

    if ( t->nrs == 0 && t->answ == 0 && t != main )
    {
        delete t;
        return 1;
    }

    return 0;
}

int apar(node *&t, char *word)
{
    if ( *word == '\0' || !t )
        return t->answ;

    int val = *word -'a';
    if ( !t->next[val] )
        return 0;

    return apar(t->next[val], word+1);
}

int pref(node *&t, char *word)
{
    if ( !t || *word == '\0' )
        return 0;

    int val = *word - 'a';
    return 1 + pref(t->next[val], word+1);
}

int main()
{
    int code;
    char word[maxa];

    node *trie = new node;
    while ( fscanf(in, "%d %s", &code, word) == 2 )
    {
        if ( code == 0 )
            insert(trie, word);
        else if ( code == 1 )
            del(trie, trie, word);
        else if ( code == 2 )
            fprintf(out, "%d\n", apar(trie, word));
        else
            fprintf(out, "%d\n", pref(trie, word) - 1);
    }

    return 0;
}