Cod sursa(job #3309623)

Utilizator AndreiNicolaescuEric Paturan AndreiNicolaescu Data 7 septembrie 2025 12:23:16
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>
#define cin ci
#define cout co
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
int c;
string s;
struct Node
{
    int apps = 0, fin = 0;
    vector<Node*> sons;
    Node():sons(26){}
    ~Node()
    {
        for(int i=0; i<26; i++)
            if(this->sons[i] != nullptr)
                delete this->sons[i];
    }
};
Node* trie = nullptr;
Node* add(Node* p, const char* w)
{
    if(p == nullptr)
        p = new Node;
    p->apps++;
    if(w[0] == '\0')
        p->fin++;
    else
        p->sons[w[0] - 'a'] = add(p->sons[w[0] - 'a'], w + 1);
    return p;
}
Node* eraze(Node *p, const char* w)
{
    if(p == nullptr)
        return p;
    if(w[0] == '\0')
        p->fin--;
    else
        p->sons[w[0] - 'a'] = eraze(p->sons[w[0] - 'a'], w + 1);
    p->apps--;
    if(p->apps == 0)
    {
        delete p;
        p = nullptr;
    }
    return p;
}
int numbapps(Node *p, const char* w)
{
    if(p == nullptr)
        return 0;
    if(w[0] == '\0')
        return p->fin;
    return numbapps(p->sons[w[0] - 'a'], w + 1);
}
int querypref(Node* p, const char* w)
{
    if(p == nullptr || w[0] == '\0')
        return 0;
    if(p->sons[w[0] - 'a'] == nullptr)
        return 0;
    return 1 + querypref(p->sons[w[0] - 'a'], w + 1);
}
int main()
{
    while(cin >> c)
    {
        cin >> s;
        if(c == 0)
            trie = add(trie, s.c_str());
        else if(c == 1)
            trie = eraze(trie, s.c_str());
        else if(c == 2)
            cout << numbapps(trie, s.c_str()) << '\n';
        else
            cout << querypref(trie, s.c_str()) << '\n';
    }
    return 0;
}