Cod sursa(job #3347810)

Utilizator andrei_nAndrei Nicolae andrei_n Data 18 martie 2026 14:05:43
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");

struct Node
{
    int nrcuv; //cate cuvinte se termina aici
    int nrap; //cate cuvinte trec pe aici
    Node *child[26];

    Node()
    {
        nrcuv = 0;
        nrap = 0;
        for (int i = 0; i < 26; i++)
            child[i] = nullptr;
    }

    void addword(string cuv, int poz = 0)
    {
        int crtchr = cuv[poz] - 'a';
        if (child[crtchr] == nullptr)
            child[crtchr] = new Node();

        child[crtchr]->nrap++;
        if (poz == cuv.size() - 1)
            child[crtchr]->nrcuv++;
        else
            child[crtchr]->addword(cuv, poz + 1);
    }

    void deleteword(string cuv, int poz = 0)
    {
        int crtchr = cuv[poz] - 'a';
        child[crtchr]->nrap--;

        if (poz == cuv.size() - 1)
        {
            child[crtchr]->nrcuv--;
            if (child[crtchr]->nrap == 0)
            {
                delete child[crtchr];
                child[crtchr] = nullptr;
            }
            return;
        }
        child[crtchr]->deleteword(cuv, poz + 1);

        if (child[crtchr]->nrap == 0)
        {
            delete child[crtchr];
            child[crtchr] = nullptr;
        }
    }

    int countap(string cuv, int poz = 0)
    {
        int crtchr = cuv[poz] - 'a';
        if (child[crtchr] == nullptr)
            return 0;

        if (poz == cuv.size() - 1)
            return child[crtchr]->nrcuv;

        return child[crtchr]->countap(cuv, poz + 1);
    }

    int longestcommonprefix(string cuv, int poz = 0)
    {
        int crtchr = cuv[poz] - 'a';
        if (child[crtchr] == nullptr)
            return 0;

        if (poz == cuv.size() - 1)
            return 1;

        return 1 + child[crtchr]->longestcommonprefix(cuv, poz + 1);
    }
};

int main()
{
    int op;
    string cuv;

    Node Trie;
    while (fin >> op >> cuv)
    {
        if (op == 0)
            Trie.addword(cuv);
        if (op == 1)
            Trie.deleteword(cuv);
        if (op == 2)
            fout << Trie.countap(cuv) << '\n';
        if (op == 3)
            fout << Trie.longestcommonprefix(cuv) << '\n';
    }
    return 0;
}