Cod sursa(job #2487689)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 5 noiembrie 2019 17:58:01
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

struct TrieNode
{
    int counter = 0;
    unordered_map<char, TrieNode*> child;

} *root = new TrieNode;


void push_tire(char* word)
{
    TrieNode* temp = root;

    for(int i = 0; word[i] != '\0'; ++i)
    {
        if(temp->child.find(word[i]) == temp->child.end())
            temp->child.insert({word[i], new TrieNode});

        temp = temp->child[word[i]];
    }

    temp->counter++;
}


TrieNode* pop_trie(char* word, TrieNode* node = root)
{
    if(word[0] == '\0')
    {
        node->counter--;
        return node;
    }

    node->child[word[0]] = pop_trie(word + 1, node->child[word[0]]);

    if(node->child[word[0]]->counter == 0 && node->child[word[0]]->child.empty() == true)
        node->child.erase(word[0]);

    return node;
}


int count_trie(char* word)
{
    TrieNode* temp = root;

    for(int i = 0; word[i] != '\0'; ++i)
        temp = temp->child[word[i]];

    return temp->counter;
}


int max_prefix(char* word)
{
    TrieNode* temp = root;
    int i;

    for(i = 0; word[i] != '\0' && temp->child.find(word[i]) != temp->child.end(); ++i)
        temp = temp->child[word[i]];


    return i;
}


int main()
{
    ifstream fin("trie.in");
    ofstream fout("trie.out");

    int op;
    char* word = new char[21];

    while(fin >> op >> word)
    {

        if(op == 0) push_tire(word);
        else if(op == 1) pop_trie(word);
        else if(op == 2) fout << count_trie(word) << '\n';
        else fout << max_prefix(word) << '\n';
    }
}