Cod sursa(job #2987563)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 2 martie 2023 14:59:02
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

struct TrieNode
{
    int counter = 0;
    int is_in_words = 0;
    TrieNode *children[30] = { NULL };
};

void Push(TrieNode *&root, string word)
{
    TrieNode *curr = root;
    int len = word.length();

    for (int i = 0; i < len; i++)
    {
        int index = word[i] - 'a';
        if (curr -> children[index] == NULL)
        {
            curr -> children[index] = new TrieNode;
        }
        curr = curr -> children[index];
        curr -> is_in_words++;
    }
    curr -> counter++;
}

void decrease(TrieNode *root, string word) {
    TrieNode *node = root;
    for(char c : word) {
        if(node->children[c - 'a'] == NULL) {
            return;
        }
        node = node->children[c - 'a'];
        node->is_in_words --;
    }
    if(node->counter > 0)
        node->counter --;
}

int search(TrieNode *root, string word) {
    TrieNode *node = root;
    for(char c : word) {
        if(node->children[c - 'a'] == NULL) {
            return 0;
        }
        node = node->children[c - 'a'];
    }
    return node->counter;
}

int maxPrefixWord(TrieNode *root, string word) {
    TrieNode *node = root;
    int current_size = 0, maximum = 0;
    for(auto c : word) {
        if(node->children[c - 'a'] == NULL) {
            return maximum;
        }
        node = node->children[c - 'a'];
        current_size ++;
        if(node->is_in_words > 0)
            maximum = current_size;
    }
    return maximum;
}

int main()
{
    TrieNode *root = new TrieNode;
    int query;
    while(f >> query) {
        string word;
        f >> word;
        if(query == 0) {
            Push(root, word);
        } else if(query == 1) {
            decrease(root, word);
        } else if(query == 2) {
            cout << search(root, word) << '\n';
        } else {
            cout << maxPrefixWord(root, word) << '\n';
        }
    }
    return 0;
}