Cod sursa(job #3362857)

Utilizator JenJenCristache Ion JenJen Data 12 august 2026 17:49:56
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <bits/stdc++.h>
using namespace std;

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

struct Trie
{
    int words;
    int cnt;
    Trie* children[26];

    Trie()
    {
        words = 0;
        cnt = 0;
        for (int i = 0; i < 26; i++)
        {
            children[i] = nullptr;
        }
    }
};

void adaug(Trie* root, char* s)
{
    if (*s == '\0')
    {
        root->words++;
        root->cnt++;
        return;
    } else
    {
        if (root->children[*s - 'a'] == nullptr)
        {
            root->children[*s - 'a'] = new Trie();
        }

        root->children[*s - 'a']->cnt++;
        adaug(root->children[*s - 'a'], s + 1);
    }
}

void sterg(Trie* root, char* s)
{
    if(*s == '\0')
    {
        root->words--;
        root->cnt--;
        return;
    } else
    {
        if (root->children[*s - 'a'] != nullptr)
        {
            root->children[*s - 'a']->cnt--;
            sterg(root->children[*s - 'a'], s + 1);
        }
    }
}

int aparitii(Trie* root, char* s)
{
    if(*s == '\0')
    {
        return root->words;
    } else
    {
        if(root->children[*s - 'a'] == nullptr || root->children[*s - 'a']->cnt == 0)
        {
            return 0;
        }

        return aparitii(root->children[*s - 'a'], s + 1);
    }
}

int val;
int prefix(Trie* root, char* s)
{
    if(*s == '\0')
    {
        return val;
    } else
    {
        if(root->children[*s - 'a'] == nullptr || root->children[*s - 'a']->cnt == 0)
        {
            return val;
        }
        val++;
        return prefix(root->children[*s - 'a'], s + 1);
    }
}

int n;
char s[25];
Trie* root = new Trie();

int main()
{
    while(in >> n >> s)
    {
        if (n == 0)
        {
            adaug(root, s);
        } else if (n == 1)
        {
            sterg(root, s);
        } else if (n == 2)
        {
            out << aparitii(root, s) << "\n";
        } else
        {
            val = 0;
            out << prefix(root, s) << "\n";
        }
    }

    return 0;
}