Cod sursa(job #1375975)

Utilizator darrenRares Buhai darren Data 5 martie 2015 15:18:02
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstring>
#include <fstream>
#include <algorithm>

using namespace std;

struct Trie
{
    int ishere, endhere;
    Trie *nxt[26];

    Trie()
    {
        ishere = endhere = 0;
        memset(nxt, 0, sizeof(nxt));
    }
};

Trie *R = new Trie();
void add(Trie *T, char *now)
{
    ++T->ishere;
    if (*now == 0)
    {
        ++T->endhere;
        return;
    }

    if (T->nxt[*now - 'a'] == 0)
        T->nxt[*now - 'a'] = new Trie();

    add(T->nxt[*now - 'a'], now + 1);
}
void rem(Trie *T, char *now)
{
    --T->ishere;
    if (*now == 0)
    {
        --T->endhere;
        return;
    }

    rem(T->nxt[*now - 'a'], now + 1);
}
int freq(Trie *T, char *now)
{
    if (*now == 0)
        return T->endhere;

    if (T->nxt[*now - 'a'] == 0)
        return 0;

    return freq(T->nxt[*now - 'a'], now + 1);
}
int pref(Trie *T, char *now)
{
    if (T->ishere == 0)
        return 0;
    if (*now == 0)
        return 1;
    if (T->nxt[*now - 'a'] == 0)
        return 1;

    return 1 + pref(T->nxt[*now - 'a'], now + 1);
}

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

    int type;
    while (fin >> type)
    {
        char aux[24];
        fin >> aux;

        if (type == 0)
            add(R, aux);
        else if (type == 1)
            rem(R, aux);
        else if (type == 2)
            fout << freq(R, aux) << '\n';
        else if (type == 3)
            fout << max(0, pref(R, aux) - 1) << '\n';
    }

    fin.close();
    fout.close();
}