Cod sursa(job #1846210)

Utilizator mihaidanielmihai daniel mihaidaniel Data 12 ianuarie 2017 12:52:04
Problema Trie Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <cstdio>
#include <cstring>

using namespace std;

struct trie
{
    trie* next[30];
    int fin, nr_cuv;
    trie()
    {
        memset( next, 0, sizeof(next) );
        fin = nr_cuv = 0;
    }
} *root = new trie;

void Insert( trie *node, char *str );
int Find( trie *node, char *s );
bool Delete( trie *node, char *s );
int Prefix( trie *node, char *s );

int main()
{
    freopen( "trie.in", "r", stdin );
    freopen( "trie.out", "w", stdout );
    char s[100];
    int x;
    while( scanf( "%d%s", &x, s ) != EOF )
    {
        switch( x )
        {
        case 0:
            Insert( root, s );
            break;
        case 1:
            if( Find( root, s) )
            {
                Delete( root, s );
            }
            break;
        case 2:
            printf( "%d\n", Find( root, s ) );
            break;
        case 3:
            printf( "%d\n", Prefix( root, s ) );
            break;
        default:
            printf("!");
        }
    }
    return 0;
}

void Insert( trie *node, char *s )
{
    //printf("Insert\n");
    ++node->nr_cuv;
    if( *s==0 )
    {
        ++node->fin;
        return;
    }
    if( !node->next[*s-'a'] )
    {
        node->next[*s-'a'] = new trie;
    }
    Insert( node->next[*s-'a'], s+1 );
}

int Find( trie *node, char *s )
{
    if( !node )
    {
        return 0;
    }
    if( *s==0 )
    {
        return node->fin;
    }
    return Find( node->next[*s-'a'], s+1 );
}

bool Delete( trie *node, char *s )
{
    //printf("Delete\n");
    if( *s==0 )
    {
        --node->fin;
        --node->nr_cuv;
    }
    else if( Delete( node->next[*s-'a'], s+1 ) )
    {
        node->next[*s-'a'] = 0;
        --node->nr_cuv;
    }
    if( node->nr_cuv == 0 && node != root )
    {
        delete node;
        return 1;
    }
    return 0;
}

int Prefix( trie *node, char *s )
{
    //printf("Prefix\n");
    if( !node->next[*s-'a'] || s==0 )
    {
        return 0;
    }
    return 1 + Prefix( node->next[*s-'a'], s+1 );
}