Cod sursa(job #1100265)

Utilizator gabrielvGabriel Vanca gabrielv Data 6 februarie 2014 19:13:13
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <cstdio>
#include <cstring>

using namespace std;

#define Char_MAX 50
#define CH (*s - 'a')

struct Trie{

    int NrSons;
    int NrWords;

    Trie *Sons[26];

    Trie() {
        NrSons = NrWords = 0;
        memset(Sons, 0, sizeof(Sons));
    }
};

Trie *T = new Trie;

char line[Char_MAX];

void Insert(Trie *node, char *s)
{
    if(*s == '\n')
    {
        node ->NrWords++;
        return;
    }

    if(node->Sons[CH] == 0)
    {
        node->Sons[CH] = new Trie;
        node->NrSons++;
    }

    Insert(node->Sons[CH], s+1);
}

bool Remove(Trie *node, char *s)
{
    if(*s == '\n')
        node->NrWords--;
    else
        if(Remove(node->Sons[CH], s+1))
        {
            node->Sons[CH] = 0;
            node->NrSons--;
        }

    if(node->NrWords == 0 && node->NrSons == 0 && node != T)
    {
        delete node;
        return true; // no words remained
    }
    return false;   // there still are words remained
}

int Aparitions(Trie *node, char *s)
{
    if(*s == '\n')
        return node->NrWords;

    if(node->Sons[CH])
        return Aparitions(node->Sons[CH], s+1);

    return 0;
}

int Prefix(Trie *node, char *s, int lenght)
{
    if(*s == '\n' || node->Sons[CH] == 0)
        return lenght;
    return Prefix(node->Sons[CH], s+1, lenght+1);
}

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

    while(fgets(line, Char_MAX - 3, stdin))
    {
        switch(int(line[0] - '0'))
        {
            case 0: Insert(T, line+2); break;
            case 1: Remove(T, line+2); break;
            case 2: printf("%d\n",Aparitions(T, line+2)); break;
            case 3: printf("%d\n",Prefix(T, line+2, 0)); break;
        }
    }

    return 0;
}