Cod sursa(job #3296998)

Utilizator Ruxandra009Ruxandra Vasilescu Ruxandra009 Data 20 mai 2025 09:57:52
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <fstream>

using namespace std;

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

struct Tnode{
    int cnt, son;
    Tnode *v[30];

    Tnode(){
        cnt = son = 0;
        for(int i = 0; i < 30; i ++) v[i] = 0;
    }
};

Tnode *root;

void add(Tnode *nod, string s, int i)
{
    if(i == s.size()){
        nod -> cnt ++;
        return ;
    }

    int ind = s[i] - 'a';
    if(!nod -> v[ind])
        nod -> v[ind] = new Tnode, nod -> son ++;

    add(nod -> v[ind], s, i + 1);
}

bool del(Tnode *nod, string s, int i)
{
    if(i == s.size())
    {
        nod -> cnt --;
        if(!nod -> cnt && !nod -> son && nod != root){
            delete nod;
            return true;
        }

        return false;
    }

    int ind = s[i] - 'a';

    if(!nod -> v[ind])
        return false;

    if(del(nod -> v[ind], s, i + 1))
        nod -> son --, nod -> v[ind] = NULL;

    if(!nod -> cnt && !nod -> son && nod != root)
    {
        delete nod;
        return true;
    }

    return false;
}

int num_word(Tnode *nod, string s, int i)
{
    if(i == s.size())
        return nod -> cnt;

    int ind = s[i] - 'a';
    if(!nod -> v[ind])
        return 0;

    return num_word(nod -> v[ind], s, i + 1);
}

int find_pref(Tnode *nod, string s, int i)
{
    if(i == s.size())
        return i;

    int ind = s[i] - 'a';

    if(!nod -> v[ind])
        return i;

    return find_pref(nod -> v[ind], s, i + 1);
}

int main()
{
    int op; string s;
    root = new Tnode;

    while(f >> op >> s)
    {
        if(op == 0)
            add(root, s, 0);

        else if(op == 1)
            del(root, s, 0);

        else if(op == 2)
            g << num_word(root, s, 0) << '\n';

        else
            g << find_pref(root, s, 0) << '\n';
    }
    return 0;
}