Cod sursa(job #2681767)

Utilizator vladm98Munteanu Vlad vladm98 Data 6 decembrie 2020 17:27:01
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

struct Node {
    Node* childs[26];
    int counter;

    Node() {
        counter = 0;
        for (int i = 0; i < 26; ++i) {
            childs[i] = nullptr;
        }
    }
};

void insert(Node* node, string s) {
    node->counter += 1;
    for (auto x : s) {
        int pos = x - 'a';
        if (node->childs[pos] == nullptr) {
            node->childs[pos] = new Node();
        }
        node = node->childs[pos];
        node->counter += 1;
    }
}

void erase(Node* node, string s) {
    node->counter -= 1;
    for (auto x : s) {
        int pos = x - 'a';
        node = node->childs[pos];
        node->counter -= 1;
    }
}

int getCounter(Node* node, string s) {
    for (auto x : s) {
        int pos = x - 'a';
        node = node->childs[pos];
    }
    int answer = node->counter;
    for (int i = 0; i < 26; ++i) {
        if (node->childs[i] != nullptr) {
            answer -= node->childs[i]->counter;
        }
    }
    return answer;
}

int getPrefix(Node* node, string s) {
    int length = 0;
    for (auto x : s) {
        int pos = x - 'a';
        if (node->childs[pos] == nullptr or node->childs[pos]->counter == 0) {
            return length;
        }
        node = node->childs[pos];
        length += 1;
    }
    return length;
}

int main()
{
    ifstream fin ("trie.in");
    ofstream fout ("trie.out");
    Node *root = new Node();
    int type;
    string s;
    while (fin >> type >> s) {
        if (type == 0) {
            insert(root, s);
        } else if (type == 1) {
            erase(root, s);
        } else if (type == 2) {
            fout << getCounter(root, s) << '\n';
        } else {
            fout << getPrefix(root, s) << '\n';
        }
    }
}