Cod sursa(job #2499000)

Utilizator melutMelut Zaid melut Data 25 noiembrie 2019 07:01:14
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.52 kb
#include <fstream>
#include <vector>
#include <string>


using namespace std;





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


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


struct Node {
    vector<Node*> sons;
    uint32_t count_ends;
    uint8_t count_sons;

    Node();
};


Node::Node() {
    sons.resize(Sigma, nullptr);
    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[word[index] - 'a'] == nullptr) {
        node.sons[word[index] - 'a'] = new Node;
        ++node.count_sons;
    }

    Insert(*(node.sons[word[index] - 'a']), 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[word[index] - 'a']->count_ends == 0)
    if (node.sons[word[index] - 'a']->count_sons == 0) {
        delete node.sons[word[index] - 'a'];
        node.sons[word[index] - 'a'] = 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;
}