Cod sursa(job #3241966)

Utilizator matei8787Matei Dobrea matei8787 Data 6 septembrie 2024 18:07:57
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.72 kb
#include <bits/stdc++.h>
using namespace std;
struct Nod
{
    Nod(){
        nr = 0;
        for ( int i = 0 ; i < 30 ; i++ )
            next[i] = NULL;
    }
    int nr;
    Nod* next[30];
};
class Trie
{
    Nod* root;
public:
    Trie(){
        root = new Nod();
    }
    void adauga(Nod* nod, string& s, int idx)
    {
        nod -> nr++;
        if ( idx == s.size() )
            return;
        if ( nod -> next[s[idx] - 'a'] == NULL )
        {
            nod->next[s[idx]-'a'] = new Nod();
        }
        adauga(nod->next[s[idx]-'a'], s, idx+1);
    }
    void add(string s)
    {
        adauga(root, s, 0);
    }
    void afiseaza(Nod* nod, string s)
    {
        cout<<s<<" "<<nod -> nr<<'\n';
        for ( char c = 'a' ; c <= 'z' ; c++ )
        {
            int nrc = c - 'a';
            if ( nod -> next[nrc] != NULL )
            {
                afiseaza(nod -> next[nrc], s + c);
            }
        }
    }
    void afis()
    {
        afiseaza(root, "");
    }
    void del(Nod* nod, string& s, int idx)
    {
        nod -> nr--;
        if ( idx == s.size() )
        {
            return;
        }
        del(nod->next[s[idx]-'a'], s, idx+1);
        if ( nod -> next[s[idx]-'a'] -> nr == 0 )
        {
            delete (nod -> next[s[idx] - 'a']);
            nod -> next[s[idx] - 'a'] = NULL;
        }
    }
    void sterge(string s)
    {
        del(root, s, 0);
    }
    int nrap(Nod* nod, string& s, int idx)
    {
        if ( idx == s.size() )
        {
            int cate = 0;
            for ( char c = 'a' ; c <= 'z' ; c++ )
            {
                if ( nod -> next[c-'a'] != NULL )
                {
                    cate += nod -> next[c-'a'] -> nr;
                }
            }
            return nod->nr - cate;
        }
        return nrap(nod->next[s[idx]-'a'], s, idx+1);
    }
    int nrap(string s)
    {
        return nrap(root, s, 0);
    }
    int maxp(Nod* nod, string& s, int idx)
    {
        if ( idx == s.size() )
        {
            return idx;
        }
        if ( nod -> next[s[idx] - 'a'] != NULL )
        {
            return maxp(nod -> next[s[idx] - 'a'], s, idx + 1);
        }
        else
        {
            return idx;
        }
    }
    int max_pref(string s)
    {
        return maxp(root, s, 0);
    }
};
ifstream in("trie.in");
ofstream out("trie.out");
int main()
{
    Trie *t = new Trie();
    int op;
    string s;
    while ( in>>op>>s )
    {
        if ( op == 0 )
        {
            t -> add(s);
        }
        else if ( op == 1 )
        {
            t -> sterge(s);
        }
        else if ( op == 2 )
        {
            out<<t->nrap(s)<<'\n';
        }
        else
        {
            out<<t->max_pref(s)<<'\n';
        }
    }
    return 0;
}