Cod sursa(job #2091693)

Utilizator LeVladzCiuperceanu Vlad LeVladz Data 20 decembrie 2017 08:37:05
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct trie
{
    int fii,nr;
    trie *f[26];
    trie ()
    {
        fii = nr = 0;
        for (int i=0;i<26;i++)
            f[i] = 0;
    }
};
trie *root = new trie;
char s[25];
int c;
void insertTrie (trie *rad, char *s)
{
    if (*s != 0)
    {
        if (rad->f[*s - 'a'] == 0)
        {
            rad->f[*s - 'a'] = new trie;
            rad->fii++;
        }
        insertTrie (rad->f[*s-'a'],s+1);
    }
    else
        rad->nr++;
}

int deleteTrie (trie *&rad, char *s)
{
    if (*s == 0)
    {
        rad->nr--;
        if (rad->nr == 0 && rad->fii == 0 && rad != root)
        {
            delete rad;
            rad = NULL;
            return 1;
        }
    }
    else
        if ( deleteTrie (rad->f[*s-'a'],s+1 ) )
        {
            rad->fii --;
            if (rad->fii == 0 && rad->nr == 0 && rad != root)
            {
                delete rad;
                rad = NULL;
                return 1;
            }
        }
    return 0;
}

int queryTrie (trie *rad,char *s)
{
    if (*s == 0)
        return rad->nr;
    if (rad->f[*s-'a'] == NULL)
        return 0;
    else
        queryTrie(rad->f[*s-'a'],s+1);
}

int prefix (trie *rad, char *s)
{
    if (*s == 0)
        return 0;
    if (rad->f[*s-'a'] == NULL)
        return 0;
    else
        return 1 + prefix (rad->f[*s-'a'],s+1);
}

int main ()
{
    while (fin>>c>>s)
    {
        if (c == 0)
            insertTrie(root,s);
        else
        {
            if (c == 1)
                deleteTrie(root,s);
            else
            {
                if (c == 2)
                    fout<<queryTrie(root,s)<<"\n";
                else
                    fout<<prefix (root,s)<<"\n";
            }
        }
    }
    return 0;
}