Cod sursa(job #2224666)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 24 iulie 2018 20:10:34
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.35 kb
#include <fstream>
#include <vector>
#include <string>
#include <map>

using namespace std;

const string IN_FILE = "trie.in";
const string OUT_FILE = "trie.out";

class Trie {
  public:
    Trie() : root(new Node()) {}

    void insert(const string& word) {
        Node* node = root;
        for (const auto& s : word) {
            if (node->sons.find(s) == node->sons.end()) {
                node->sons[s] = new Node();
            }
            node->size++;
            node = node->sons[s];
        }
        node->size++;
        node->count++;
    }

    int count(const string& word) const {
        Node* node = root;
        for (const auto& s: word) {
            if (node->sons.find(s) == node->sons.end()) return 0;
            node = node->sons[s];
        }
        return node->count;
    }

    int longestCommonPrefix(const string& word) const {
        Node* node = root;
        int length = 0;
        for (const auto& s : word) {
            if (node->sons.find(s) == node->sons.end()) return length;
            length++;
            node = node->sons[s];
        }
        return length;
    }

    void erase(const string& word) {
        erase(root, word, 0);
    }

    ~Trie() {
        clear(root);
    }

  private:
    struct Node {
        map<char, Node*> sons;
        int size, count;
    };

    Node* root;

    bool erase(Node* node, const string& word, const int i) {
        node->size--;
        if (i == int(word.length())) {
            node->count--;
        } else {
            const char s = word[i];
            if (erase(node->sons[s], word, i + 1)) {
                delete node->sons[s];
                node->sons.erase(s);
            }
        }
        return node->size == 0;
    }

    void clear(Node* node) {
        for (const auto& it : node->sons) {
            clear(it.second);
        }
        node->sons.clear();
        delete node;
    }
};

int main() {
    ifstream in(IN_FILE);
    ofstream out(OUT_FILE);
    auto trie = Trie();
    int type;
    string word;
    while (in >> type >> word) {
        if (type == 0) {
            trie.insert(word);
        } else if (type == 1) {
            trie.erase(word);
        } else if (type == 2) {
            out << trie.count(word) << "\n";
        } else {
            out << trie.longestCommonPrefix(word) << "\n";
        }
    }
    in.close();
    out.close();
    return 0;
}