Cod sursa(job #2142210)

Utilizator jeanFMI - Petcu Ion Cristian jean Data 24 februarie 2018 20:53:53
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
using namespace std;

struct Trie {
    int count;
    unordered_map<char, Trie*> children;

    Trie() {
        count = 0;
    }
};

void add(Trie *&node, const string& word, int word_index) {
    if (word_index == word.size()) {
        node->count++;
        return;
    }
    char c = word[word_index];
    if (node->children.find(c) == node->children.end()) {
        node->children[c] = new Trie();
    }
    add(node->children[c], word, word_index + 1);
}

bool remove(Trie *&node, const string& word, int word_index) {
    if (word_index == word.size()) {
        node->count--;
        return node->count == 0 && node->children.size() == 0;
    }
    char c = word[word_index];
    bool rm = remove(node->children[c], word, word_index + 1);
    if (rm) {
        node->children.erase(c);
        return node->count == 0 && node->children.size() == 0;
    }
    return false;
}

int search(Trie *&node, const string& word, int word_index) {
    if (word_index == word.size()) {
        return node->count;
    }
    char c = word[word_index];
    if (node->children.find(c) == node->children.end()) {
        return 0;
    }
    return search(node->children[c], word, word_index + 1);
}

int query(Trie *&node, const string& word, int word_index, int depth) {
    if (word_index == word.size()) {
        return depth;
    }
    char c = word[word_index];
    if (node->children.find(c) == node->children.end()) {
        return depth;
    }
    return query(node->children[c], word, word_index + 1, depth + 1);
}

int main() {
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    
    Trie* root = new Trie();
    int op, ret;
    string word;

    while(cin >> op) {
        cin >> word;
        if (op == 0) add(root, word, 0);
        else if (op == 1) remove(root, word, 0);
        else if (op == 2) cout << search(root, word, 0) << endl;
        else cout << query(root, word, 0, 0) << endl;
    }

    return 0;
}