Cod sursa(job #3321533)

Utilizator and_Turcu Andrei and_ Data 9 noiembrie 2025 23:17:58
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
#include <fstream>
#include <cstring>
// #include <memory>

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


const int alphabet_size = 30;

class nod{
public: 
    nod * next[alphabet_size];
    int ct, end;
    nod() : ct(0), end(0)
    {
        for(int i = 0; i < alphabet_size; i++)
            this->next[i] = NULL;
    }
};


void add(nod *nod_trie, std::string &s, int poz)
{
    nod_trie->ct ++;
    if(poz == s.size())
    {
        nod_trie->end ++;
        return;
    }

    int letter = s[poz] - 'a';
    if(nod_trie->next[letter] == NULL)
    {
        nod *new_nod = new nod;
        nod_trie->next[letter] = new_nod;    
    }    

    add(nod_trie->next[letter], s, poz + 1);
}

void del(nod *nod_trie, std::string &s, int poz)
{
    nod_trie->ct --;
    
    if(poz == s.size())
    {
        nod_trie->end--;
        return;
    }

    int letter = s[poz] - 'a';
    
    del(nod_trie->next[letter], s, poz + 1);

    if(nod_trie->next[letter]->ct == 0)
    {
        delete nod_trie->next[letter];
        nod_trie->next[letter] = NULL;
    }
}

int count(nod *nod_trie, std::string &s, int pos)
{
    if(pos == s.size())
        return nod_trie->end;
    else if( nod_trie == NULL)
        return 0;

    int letter = s[pos] - 'a';

    return count(nod_trie->next[letter], s, pos + 1);
}

int pref(nod *node_tire, std::string s, int pos)
{
    if(node_tire == NULL)
        return 0;

    int letter = s[pos] - 'a';

    int match = 0;
    if( node_tire->next[letter] != NULL )
        match ++;

    return match + pref(node_tire->next[letter], s, pos + 1);
}


int main()
{
    nod *start_trie = new nod;

    int op;
    std::string s;
    while(fin >> op >> s)
    {
        op++;
        if(op == 1)
            add(start_trie, s, 0);
        else if(op == 2)
            del(start_trie, s, 0);
        else if(op == 3)
            fout << count(start_trie, s, 0) << "\n";        
        else 
            fout << pref(start_trie, s, 0) << "\n";
    }

    fin.close();
    fout.close();

    return 0;

// execpt
}