Cod sursa(job #2499003)

Utilizator melutMelut Zaid melut Data 25 noiembrie 2019 08:02:17
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.41 kb
#include <fstream>
#include <cstring>
#include <string>


#define SIGMA 26


using namespace std;


char const in_file[] = "trie.in";
char const out_file[] = "trie.out";


ifstream Read(in_file);
ofstream Write(out_file);


struct Node {
    Node *sons[SIGMA];
    uint32_t count_ends;
    uint8_t count_sons;

    Node();
};


Node::Node() {
    memset(sons, (int)nullptr, sizeof(sons));
    count_ends = 0;
    count_sons = 0;
}


Node root;


void Insert(
    Node &node,
    string const &word,
    uint8_t const index
) {
    if (index == word.size()) {
        ++node.count_ends;
        return;
    }

    uint8_t ch = word[index] - 'a';

    if (node.sons[ch] == nullptr) {
        node.sons[ch] = new Node;
        ++node.count_sons;
    }

    Insert(*(node.sons[ch]), word, index + 1);
}


void Delete(
    Node &node,
    string const &word,
    uint8_t const index
) {
    if (index == word.size()) {
        --node.count_ends;
        return;
    }

    uint8_t ch = word[index] - 'a';

    Delete(*(node.sons[word[index] - 'a']), word, index + 1);

    if (node.sons[ch]->count_ends == 0)
    if (node.sons[ch]->count_sons == 0) {
        delete node.sons[ch];
        node.sons[ch] = nullptr;
        --node.count_sons;
    }
}


uint32_t Count(
    Node &node,
    string const &word,
    uint8_t const index
) {
    if (index == word.size()) {
        return node.count_ends;
    }

    if (node.sons[word[index] - 'a'] != nullptr) {
        return Count(*(node.sons[word[index] - 'a']), word, index + 1);
    }

    return 0;
}


uint16_t PrefixLength(
    Node &node,
    string const &word,
    uint8_t const index
) {
    if (index == word.size()) {
        return index;
    }

    if (node.sons[word[index] - 'a'] == nullptr) {
        return index;
    }

    return PrefixLength(*(node.sons[word[index] - 'a']), word, index + 1);
}


int main() {
    uint16_t query;
    string word;

    while (Read >> query >> word) {
        if (query == 0) {
            Insert(root, word, 0);
        }
        else if (query == 1) {
            Delete(root, word, 0);
        }
        else if (query == 2) {
            Write << Count(root, word, 0) << '\n';
        }
        else {
            Write << PrefixLength(root, word, 0) << '\n';
        }
    }

    Read.close();
    Write.close();

    return 0;
}