Cod sursa(job #2952950)

Utilizator Stefan_GhinescuGhinescu Stefan-George Stefan_Ghinescu Data 10 decembrie 2022 11:26:31
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <string>

#define notlocal 1

#if !notlocal

#include <iostream>
#define fin std::cin
#define fout std::cout

#else

#include <fstream>
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");

#endif

using namespace std;

struct nod
{
    int val;
    int num;
    nod* copii[26];
    nod()
        : val(0), num(0)
    {
        for (int i = 0; i < 26; ++i)
        {
            copii[i] = nullptr;
        }
    }
};

void add(nod*& node, const char* s)
{
    if (node == nullptr)
    {
        node = new nod;
    }
    ++node->num;
    if (!s[0])
    {
        ++node->val;
    }
    else
    {
        add(node->copii[s[0] - 'a'], s + 1);
    }
}

void sub(nod*& node, const char* s)
{
    --node->num;
    if (!s[0])
    {
        --node->val;
    }
    else
    {
        sub(node->copii[s[0] - 'a'], s + 1);
    }
    /**if (!node->num)
    {
        delete node;
        node = nullptr;
    }*/
}

int query(nod*& node, const char* s)
{
    if (node == nullptr)
    {
        return 0;
    }
    if (!s[0])
    {
        return node->val;
    }
    return query(node->copii[s[0] - 'a'], s + 1);
}

int prefix(nod*& node, const char* s, int val)
{
    if (node == nullptr)
    {
        return -1;
    }
    if (node->num != val)
    {
        return 1 + prefix(node->copii[s[0] - 'a'], s + 1, val);
    }
    return -1;
}

int main()
{
    nod* root = nullptr;
    short int a;
    string w;
    while (fin >> a >> w)
    {
        switch (a)
        {
        case 0:
            add(root, w.c_str());
            break;
        case 1:
            if (query(root, w.c_str()))
            {
                sub(root, w.c_str());
            }
            break;
        case 2:
            fout << query(root, w.c_str()) << '\n';
            break;
        case 3:
            if (root == nullptr)
            {
                fout << "0\n";
                break;
            }
            fout << prefix(root, w.c_str(), query(root, w.c_str())) << '\n';
            break;
        }
    }
    return 0;
}