Cod sursa(job #751063)

Utilizator andumMorie Daniel Alexandru andum Data 24 mai 2012 02:25:24
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <cstring>

#define CHR (*s - 'a')

using namespace std;

class Trie
{
    int cnt, sons;
    Trie *son[26];

    public:
        Trie();
        void insert(char*);
        bool erase(char*);
        int count(char*);
        int prefix(char*, int);
} *T;

Trie::Trie()
{
    cnt = sons = 0;
    memset(son, 0, sizeof(son));
}

void Trie::insert(char *s)
{
    if (*s == '\0')
    {
        this->cnt++;
        return;
    }

    if (!this->son[CHR])
    {
        this->son[CHR] = new Trie;
        this->sons++;
    }

    this->son[CHR]->insert(s+1);
}

bool Trie::erase(char *s)
{
    if (*s == '\0')
    {
        this->cnt--;
    }
    else if (this->son[CHR]->erase(s+1))
    {
        this->son[CHR] = 0;
        this->sons--;
    }

    if (!this->cnt && !this->sons && this != T)
    {
        delete this;
        return 1;
    }
    return 0;
}

int Trie::count(char *s)
{
    if(*s == '\0')
        return this->cnt;

    if(this->son[CHR])
        return this->son[CHR]->count(s+1);
    return 0;
}

int Trie::prefix(char *s, int k)
{
    if(*s == '\0' || !this->son[CHR])
        return k;
    return this->son[CHR]->prefix(s+1, k+1);
}

int main()
{
    ifstream in("trie.in");
    ofstream out("trie.out");

    T = new Trie;

    char s[30];

    while (in.getline(s, 30))
    {
        switch (s[0])
        {
            case '0':
                T->insert(s+2);
                break;
            case '1':
                T->erase(s+2);
                break;
            case '2':
                out<<T->count(s+2)<<'\n';
                break;
            case '3':
                out<<T->prefix(s+2, 0)<<'\n';
                break;
        }
    }

    return 0;
}