Cod sursa(job #1164120)

Utilizator cbanu96Banu Cristian cbanu96 Data 1 aprilie 2014 20:59:16
Problema Trie Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <cstdio>

using namespace std;

#define FILEIN "trie.in"
#define FILEOUT "trie.out"

class Trie {
    public:
    Trie() {
        for ( int i = 0; i < 26; i++ ) {
            this->Sons[i] = nullptr;
        }
    }

    ~Trie() {
        fprintf(stderr, "Deleting Trie Sons...");

        for ( int i = 0; i < 26; i++ ) {
            if (this->Sons[i] != nullptr)
                delete this->Sons[i];
        }

        fprintf(stderr, "Deleting Trie... DONE!");
    }

    void Insert(const char *str) {
        if (*str == '\n' || *str == 0) {
            this->_Count++;
            return;
        }

        if (this->Sons[*str - 'a'] == nullptr)
            this->Sons[*str - 'a'] = new Trie(),
            this->_NrSons++;

        this->Sons[*str - 'a']->Insert(str+1);
    };

    int Delete(const char *str) {
        if (*str == '\n' || *str == 0)
            this->_Count--;
        else
        if (this->Sons[*str - 'a']->Delete(str+1) ) {
            delete this->Sons[*str - 'a'];
            this->Sons[*str - 'a'] = nullptr;
            this->_NrSons--;
        }

        if (this->_Count == 0 && this->_NrSons == 0) {
            return 1;
        }

        return 0;
    };

    int Query(const char *str) {
        if (*str == '\n' || *str == 0)
            return this->_Count;

        if (this->Sons[*str - 'a'])
            return this->Sons[*str - 'a']->Query(str + 1);

        return 0;
    };

    int Prefix(const char *str) {
        if (*str == '\n' || *str == 0 || this->Sons[*str - 'a'] == 0)
            return 0;

        return this->Sons[*str - 'a']->Prefix(str+1) + 1;
    };

private:
    Trie *Sons[26];
    int _Count;
    int _NrSons;
};

Trie *trie = new Trie();

int main() {
    freopen(FILEIN, "r", stdin);
    freopen(FILEOUT, "w", stdout);

    char buffer[32];

    fgets(buffer, 32, stdin);
    do {
        if (buffer[0] == '0') {
            trie->Insert(buffer+2);
        } else if (buffer[0] == '1') {
            trie->Delete(buffer+2);
        } else if (buffer[0] == '2') {
            printf("%d\n", trie->Query(buffer+2));
        } else if (buffer[0] == '3') {
            printf("%d\n", trie->Prefix(buffer+2));
        }

        fgets(buffer, 32, stdin);
    } while(!feof(stdin));

    //delete trie;

    return 0;
}