Cod sursa(job #3140459)

Utilizator ciacliboiiiciacli stefan ciacliboiii Data 6 iulie 2023 16:17:54
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");

struct Node
{
    int cnt_nod, cnt_sub;
    Node *next[26];
    Node() : cnt_nod(0), cnt_sub(0), next{} {}
};
void Insert(Node *root, const char *w)
{
    root -> cnt_sub += 1;
    if(*w == '\0')
    {
        root -> cnt_nod += 1;
        return;
    }
    int c = *w - 'a';
    if(root -> next[c] == nullptr)
    {
        root -> next[c] = new Node();
    }
    Insert(root -> next[c], w + 1);

}
void Erase(Node *root, const char *w)
{
    root -> cnt_sub -= 1;
    if(*w == '\0')
    {
        root -> cnt_nod -= 1;
        return;
    }
    int c = *w - 'a';
    Erase(root -> next[c], w + 1);
    if(root -> next[c] -> cnt_sub == 0)
    {
        delete root -> next[c];
        root -> next[c] = nullptr;
    }


}
int Find(Node *root, const char *w)
{
    if(*w == '\0')
    {
        return root -> cnt_nod;
    }
    int c = *w - 'a';
    if(root -> next[c] == nullptr)
        return 0;
    return Find(root->next[c], w + 1);

}
int Pref(Node *root, const char *w)
{
    if(*w == '\0')
        return 0;
    int c = *w - 'a';
    if(root -> next[c] == nullptr)
        return 0;
    return Pref(root -> next[c], w + 1) + 1;
}
int main()
{
    Node* root = new Node();
    int op;
    char w[25];
    while(fin >> op >> w)
    {
        switch (op)
        {
            case 0:
                Insert(root, w);
                break;
            case 1:
                Erase(root, w);
                break;
            case 2:
                fout << Find(root, w) << '\n';
                break;
            case 3:
                fout << Pref(root, w) << '\n';
                break;
        }

    }
    return 0;
}