Cod sursa(job #3281548)

Utilizator SergiuS3003Sergiu Stancu Nicolae SergiuS3003 Data 2 martie 2025 12:05:33
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.35 kb
#include <iostream>
#include <fstream>
#include <list>

using namespace std;

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

struct Trie
{
    int nrCuv, nrAp;
    Trie *fii[26];

    Trie()
    {
        nrCuv = 0, nrAp = 0;
        for (int i = 0; i < 26; i++)
        {
            fii[i] = nullptr;
        }
    }

    void addWord(const string &str, int poz = 0)
    {
        int crtCh = str[poz] - 'a';
        if (fii[crtCh] == nullptr)
        {
            fii[crtCh] = new Trie();
        }
        fii[crtCh]->nrAp++;
        if (poz == str.size() - 1)
        {
            fii[crtCh]->nrCuv++;
        }
        else
            fii[crtCh]->addWord(str, poz + 1);
    }

    void deleteWord(const string &str, int poz = 0)
    {
        int crtCh = str[poz] - 'a';
        fii[crtCh]->nrAp--;
        if (poz == str.size() - 1) // trebuie sa ne oprim cu totul
        {
            fii[crtCh]->nrCuv--;
            if (fii[crtCh]->nrAp == 0) // nu mai este niciun motiv sa tinem nodul
            {
                delete fii[crtCh];
                fii[crtCh] = nullptr;
            }
            return;
        }
        fii[crtCh]->deleteWord(str, poz + 1); // stergem in continuare
        if (fii[crtCh]->nrAp == 0)
        {
            delete fii[crtCh]; // dealocam memoria in cazul in care nu mai e nevoie de ea
            fii[crtCh] = nullptr;
        }
    }

    int countAp(const string &str, int poz = 0)
    {
        int crtCh = str[poz] - 'a';
        if (poz == str.size() - 1)
            return fii[crtCh]->nrCuv;
        return fii[crtCh]->countAp(str, poz + 1);
    }

    int longestCommonPrefix(const string &str, int poz = 0)
    {
        int crtCh = str[poz] - 'a';
        if (fii[crtCh] == nullptr)
        {
            return 0;
        }
        if (poz == str.size() - 1)
        {
            return 1;
        }
        return 1 + fii[crtCh]->longestCommonPrefix(str, poz + 1);
    }
};

int main()
{
    int op;
    string str;
    Trie T;
    while (f >> op >> str)
    {
        switch (op)
        {
            case 0:
                T.addWord(str);
                break;
            case 1:
                T.deleteWord(str);
                break;
            case 2:
                g << T.countAp(str) << '\n';
                break;
            case 3:
                g << T.longestCommonPrefix(str) << '\n';
        }
    }
    return 0;
}