Cod sursa(job #2224773)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 25 iulie 2018 00:51:08
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.65 kb
#include <bits/stdc++.h>

using namespace std;

constexpr int SIGMA = 26;

class Trie{
private:

    class Node{
    public:
        vector<Node*> children;
        int cnt;
        int num_kids;

        Node(){
            cnt = 0;
            num_kids = 0;
            children.resize(SIGMA);
        }
    };

    Node* root;

public:

    Trie(){
        root = new Node();
    }

    void insert(const string& text){
        Node* node = root;

        for (char c: text){
            int id = c - 'a';

            if (node->children[id] == nullptr){
                node->num_kids++;
                node->children[id] = new Node();
            }

            node = node->children[id];
        }

        node->cnt++;
    }

    void erase(const string& text){
        Node* node = root;
        vector<Node*> path;

        for (char c: text){
            path.push_back(node);
            int id = c - 'a';

            if (node->children[id] == nullptr){
                return;
            }

            node = node->children[id];
        }

        path.push_back(node);
        node->cnt--;
        int k = (int)path.size() - 1;

        while (node->cnt == 0 && node->num_kids == 0){
            if (node == root)
                break;

            auto parent = path[--k];

            for (auto &c: parent->children)
                if (c == node){
                    parent->num_kids--;
                    delete c;
                    c = nullptr;
                    break;
                }

            node = parent;
        }
    }

    int maxPrefix(const string& text){
        Node* node = root;
        int k = 0;

        for (char c: text){
            int id = c - 'a';

            if (node->children[id] == nullptr){
                return k;
            }

            k++;
            node = node->children[id];
        }

        return k;
    }

    int count(const string& text){
        Node* node = root;

        for (char c: text){
            int id = c - 'a';

            if (node->children[id] == nullptr){
                return 0;
            }

            node = node->children[id];
        }

        return node->cnt;
    }
};

int main() {
//    ifstream cin("data.txt");
    ifstream cin("trie.in");
    ofstream cout("trie.out");

    ios_base::sync_with_stdio(false);

    int t;
    string text;
    Trie trie;

    while (cin >> t >> text){
        if (t == 0){
            trie.insert(text);
        }
        else if (t == 1){
            trie.erase(text);
        }
        else if (t == 2){
            cout << trie.count(text) << "\n";
        }
        else{
            cout << trie.maxPrefix(text) << "\n";
        }
    }

    return 0;
}