Cod sursa(job #2676467)

Utilizator Rares31100Popa Rares Rares31100 Data 24 noiembrie 2020 13:40:58
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <bits/stdc++.h>

using namespace std;

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

struct nod
{
    int apar = 0;
    nod* lit[26];
}*Top;

void adauga(string cuv)
{
    nod* curent = Top;

    for(auto l:cuv)
        if(curent -> lit[l-'a'] == NULL)
        {
            nod* nou = new nod();
            curent -> lit[l-'a'] = nou;
            curent = nou;
        }
        else
            curent = curent -> lit[l-'a'];

    curent -> apar++;
}

int numara(string cuv)
{
    nod* curent = Top;

    for(auto l:cuv)
        if(curent -> lit[l-'a'] == NULL)
            return 0;
        else
            curent = curent -> lit[l-'a'];

    return curent -> apar;
}

void sterge(string cuv)
{
    nod* curent = Top;
    stack <nod*> adrese;
    adrese.push(Top);

    for(auto l:cuv)
        if(curent -> lit[l-'a'] == NULL)
            return;
        else
        {
            curent = curent -> lit[l-'a'];
            adrese.push(curent);
        }

    if(curent -> apar > 0)
        curent -> apar--;

    for(int i = 1; i <= adrese.size() - 1; i++)
    {
        nod* test = adrese.top();
        adrese.pop();

        if(test -> apar > 0)
            break;

        bool ok = true;
        for(auto adr : test -> lit)
            if(adr != NULL)
            {
                ok = false;
                break;
            }

        if(ok == false)
            break;
        else
        {
            delete test;
            adrese.top() -> lit[cuv[cuv.size() - i] - 'a'] = NULL;
        }
    }
}

int prefix(string cuv)
{
    nod* curent = Top;
    int nr = 0, maxx = 0;

    for(auto l:cuv)
        if(curent -> lit[l-'a'] != NULL)
        {
            curent = curent -> lit[l-'a'];
            nr++;

            if(curent -> apar)
                maxx = nr;
        }
        else
            break;

    return maxx;
}

int main()
{
    Top = new nod();

    int c;
    string cuv;

    while(in >> c)
    {
        in >> cuv;

        switch(c)
        {
            case 0: adauga(cuv); break;
            case 1: sterge(cuv); break;
            case 2: out << numara(cuv) << '\n'; break;
            case 3: out << prefix(cuv) << '\n'; break;
        }
    }

    return 0;
}