Cod sursa(job #528219)

Utilizator darrenRares Buhai darren Data 2 februarie 2011 13:53:08
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <cstring>
#include <fstream>
#include <string>

using namespace std;

#define C (*S - 'a')

struct Trie
{
    int sons, ends;
    Trie* son[26];

    Trie()
    {
        sons = ends = 0;
        memset(son, 0, sizeof(son));
    }
};
Trie* T = new Trie;

void insert(Trie* nod, char* S)
{
    if (*S == '\0')
    {
        ++nod->ends;
        return;
    }
    if (nod->son[C] == 0)
    {
        Trie* noda = new Trie;
        nod->son[C] = noda;
        ++nod->sons;
    }

    insert(nod->son[C], S + 1);
}
int erase(Trie* nod, char* S)
{
    if (*S == '\0')
        --nod->ends;
    else if (erase(nod->son[C], S + 1))
    {
        --nod->sons;
        nod->son[C] = 0;
    }

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

    return 0;
}
int findword(Trie* nod, char* S)
{
    if (*S == '\0')
        return nod->ends;

    if (nod->son[C] != 0)
        return findword(nod->son[C], S + 1);
    return 0;
}
int findprefix(Trie* nod, char* S, int K)
{
    if (*S == '\0')
        return K;
    else
    {
        if (nod->son[C] != 0)
            return findprefix(nod->son[C], S + 1, K + 1);
        return K;
    }
}

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

    char now[30];
    while (fin.getline(now, 30))
        switch (now[0])
        {
            case '0':
                insert(T, now + 2);
                break;
            case '1':
                erase(T, now + 2);
                break;
            case '2':
                fout << findword(T, now + 2) << '\n';
                break;
            case '3':
                fout << findprefix(T, now + 2, 0) << '\n';
                break;
        }

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