Cod sursa(job #1338447)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 10 februarie 2015 01:59:13
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <cstring>
using namespace std;

ifstream is("trie.in");
ofstream os("trie.out");

struct Trie{
    Trie()
    {
        memset(fii, 0, sizeof(fii));
    }
    int nrfii = 0, nrcuv = 0;
    Trie* fii[26];
};

int tip;
Trie* t = new Trie;
char cuv[30];

void Insert(Trie* nod, char *s);
bool Delete(Trie* nod, char *s);
void Count(Trie* nod, char *s);
int Prefix(Trie* nod, char *s);

int main()
{
    while ( is.getline(cuv, 30) )
    {
        tip = cuv[0] - '0';
        if ( !tip ) Insert(t, cuv + 2);
        else
            if ( tip == 1 ) Delete(t, cuv + 2);
            else
                if ( tip == 2 ) Count(t, cuv + 2);
                else os << Prefix(t, cuv + 2) << "\n";
    }
    is.close();
    os.close();
    return 0;
}

int Prefix(Trie* nod, char *s)
{
    if ( *s == '\0' || !nod->fii[*s - 'a'] )
        return 0;
    return 1 + Prefix(nod->fii[*s - 'a'], s + 1);
}

void Count(Trie* nod, char *s)
{
    if ( *s == '\0' )
    {
        os << nod->nrcuv << "\n";
        return;
    }
    if ( nod->fii[*s - 'a'] )
        Count(nod->fii[*s - 'a'], s + 1);
    else
        os << "0\n";
}

bool Delete(Trie* nod, char *s)
{
    if ( *s == '\0' )
        --nod->nrcuv;
    else
        if ( Delete(nod->fii[*s - 'a'], s + 1) )
        {
            nod->fii[*s - 'a'] = 0;
            --nod->nrfii;
        }
    if ( !nod->nrcuv && !nod->nrfii && nod != t )
    {
        delete nod;
        return true;
    }
    return false;
}

void Insert(Trie* nod, char *s)
{
    if ( *s == '\0' )
    {
        ++nod->nrcuv;
        return;
    }
    if ( !nod->fii[*s - 'a'] )
    {
        nod->fii[*s - 'a'] = new Trie;
        ++nod->nrfii;
    }
    Insert(nod->fii[*s - 'a'], s + 1);
}