Cod sursa(job #3307258)

Utilizator AndreiEsteNebunAndrei Mateescu AndreiEsteNebun Data 19 august 2025 13:22:08
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

string filename = "trie";

ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

struct Node
{
    Node* copii[26];
    int fr;
};

void ins(Node* node, string s)
{
    node->fr++;
    for(auto it : s)
    {
        int pos = it - 'a';
        if(node->copii[pos] == nullptr)
        {
            node->copii[pos] = new Node();
        }
        node = node->copii[pos];
        node->fr++;
    }
}

void er(Node* node, string s)
{
    node->fr--;
    for(auto it : s)
    {
        int pos = it - 'a';
        node = node->copii[pos];
        node->fr--;
    }
}

int aparitii(Node* node, string s)
{
    for(auto it : s)
    {
        int pos = it - 'a';
        if(node->copii[pos] == nullptr)
            return 0;
        node = node->copii[pos];
    }
    int ans = node->fr;
    for(int i = 0; i < 26; i++)
    {
        if(node->copii[i] != nullptr)
        {
            ans -= node->copii[i]->fr;
        }
    }
    return ans;
}

int prefix(Node* node, string s)
{
    int length = 0;
    for (auto it : s)
    {
        int pos = it - 'a';
        if (node->copii[pos] == nullptr or node->copii[pos]->fr == 0)
        {
            return length;
        }
        node = node->copii[pos];
        length += 1;
    }
    return length;
}

int main()
{
    Node *root = new Node();
    int type;
    string s;
    while(fin >> type >> s)
    {
        if (type == 0)
        {
            ins(root, s);
        }
        else if (type == 1)
        {
            er(root, s);
        }
        else if (type == 2)
        {
            fout << aparitii(root, s) << '\n';
        }
        else
        {
            fout << prefix(root, s) << '\n';
        }
    }
}