Cod sursa(job #581362)

Utilizator cmiNCosmin Poieana cmiN Data 14 aprilie 2011 00:43:42
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
#include <string>

using namespace std;

struct Trie {
    unsigned int wcnt, scnt;
    Trie* sons[26];
    Trie()
    {
        wcnt = scnt = 0;
        for (unsigned short int i = 0; i < 26; i++) {
            sons[i] = 0;
        }
    }
};

string mystr;
Trie* root = new Trie;

unsigned short int dec(const char chr)
{
    return (unsigned short int) (chr - 'a');
}

void add(Trie* pobj, unsigned short int poz)
{
    if (mystr[poz]) {
        if (!(pobj->sons[dec(mystr[poz])])) {
            pobj->sons[dec(mystr[poz])] = new Trie;
            pobj->scnt++;
        }
        add(pobj->sons[dec(mystr[poz])], poz + 1);
    } else {
        pobj->wcnt++;
    }
}

bool del(Trie* pobj, unsigned short int poz)
{
    if (!mystr[poz]) {
        pobj->wcnt--;
    } else if (del(pobj->sons[dec(mystr[poz])], poz + 1)) {
        pobj->scnt--;
        pobj->sons[dec(mystr[poz])] = 0;
    }
    if (pobj != root && !(pobj->wcnt) && !(pobj->scnt)) {
        delete pobj;
        return 1;
    } else {
        return 0;
    }
}

unsigned int count(Trie* pobj, unsigned short int poz)
{
    if (mystr[poz]) {
        return count(pobj->sons[dec(mystr[poz])], poz + 1);
    } else {
        return pobj->wcnt;
    }
}

unsigned int pref(Trie* pobj, unsigned short int poz, unsigned int nr)
{
    if (!mystr[poz] || !pobj->sons[dec(mystr[poz])]) {
        return nr;
    } else {
        return pref(pobj->sons[dec(mystr[poz])] , poz + 1, nr + 1);
    }
}

int main()
{
    unsigned short int op;
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    while (fin.good()) {
        fin >> op >> mystr;
        switch (op) {
        case 0:
            add(root, 0);
            break;
        case 1:
            del(root, 0);
            break;
        case 2:
            fout << count(root, 0) << endl;
            break;
        case 3:
            fout << pref(root, 0, 0) << endl;
            break;
        }
    }
    fin.close();
    fout.close();
    return 0;
}