Cod sursa(job #1092010)

Utilizator gbi250Gabriela Moldovan gbi250 Data 26 ianuarie 2014 14:29:16
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.14 kb
#include <cstring>
#include <cstdio>
#define MAX_LEN_WORD 21
#define MAX_LEN 30

using namespace std;

struct node{
    int freq, sons;
    node *next[MAX_LEN];

    node()
    {
        freq = sons = 0;
        memset(next, 0, sizeof(next));
    }
};

node * root = new node;

char word[MAX_LEN_WORD];
int op;

inline void ins_word( node *crt_node, char *s );
inline bool del_word( node *crt_node, char *s );
inline int word_freq( node *crt_node, char *s );
inline int longest_prefix( node *crt_node, char *s, int level );

int main()
{
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    while( scanf("%d %s", &op, word) == 2 )
    {
        if( op == 0 )
            ins_word(root, word);

        else if( op == 1 )
                del_word(root, word);

        else if( op == 2 )
            printf("%d\n", word_freq(root, word));

        else
            printf("%d\n", longest_prefix(root, word, 0));
    }
    return 0;
}

inline void ins_word( node *crt_node, char *s )
{
    if( *s == '\0' )
        ++crt_node -> freq;
    else
    {
        if( ! crt_node -> next[ *s - 'a' ] )
        {
            crt_node -> next[ *s - 'a' ] = new node;
            ++crt_node -> sons;
        }
        ins_word( crt_node ->  next[ *s - 'a' ], s + 1);
    }
}

inline bool del_word( node *crt_node, char *s )
{
    if( *s == '\0' )
        --crt_node -> freq;
    else
        if( del_word( crt_node -> next[ *s - 'a' ], s + 1) )
        {
            crt_node -> next[ *s - 'a' ] = 0;
            --crt_node -> sons;
        }
    if( !crt_node -> freq && !crt_node -> sons && crt_node != root)
    {
        delete crt_node;
        return 1;
    }
    return 0;
}


inline int word_freq( node *crt_node, char *s )
{
    if( *s == '\0' )
        return crt_node -> freq;
    else
        if( crt_node -> next[ *s - 'a' ] )
            return word_freq( crt_node -> next[ *s - 'a' ], s + 1 );
       else
            return 0;
}

inline int longest_prefix( node *crt_node, char *s, int level )
{
    if( *s == '\0' || ! crt_node -> next[ *s - 'a' ])
        return level;
    else
        return longest_prefix( crt_node -> next[ *s - 'a'], s + 1, level + 1);
}