Cod sursa(job #2814156)

Utilizator Andrei012Trache Andrei Andrei012 Data 7 decembrie 2021 17:41:28
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
char sir[27];
class node
{
public:
    int nr_a=0;
    int nr_c=0;
    vector<node*> fiu;

    node() {
        fiu.resize(26, NULL);
    }
};

class Trie
{
node* root=NULL;
public:
    void ins(char* s){
        root=insert_(s, root);
    }

    void er(char* s){
        root=erase_(s, root);
    }

    int q_pref(char* s){
        return prefix(s,root);
    };

    int q_cate(char* s){
       return cat(s,root);
    };
private:
    node* erase_(char* s, node* nod);
    node* insert_(char* s, node* nod);
    int prefix(char* s, node* nod);
    int cat(char* s, node* nod);
};


node* Trie::erase_(char* s, node* nod)
{
    if(nod== NULL)
        return nod;
    nod->nr_a--;
    if(s[0]==NULL)
        nod->nr_c--;
    else{
        nod->fiu[s[0]-'a']=erase_(s+1, nod->fiu[s[0]-'a']);
    }
    if(nod->nr_a==0){
        delete nod;
        nod=NULL;
    }
    return nod;
}

node* Trie::insert_(char* s, node* nod){
    if(nod==NULL)
        nod = new node;
    ++nod->nr_a;
    if(s[0]==NULL)
        ++nod->nr_c;
    else
        nod->fiu[s[0]-'a']=insert_(s+1,nod->fiu[s[0]-'a']);
    return nod;

}

int Trie::prefix(char* s, node* nod){

    if(nod == NULL || s[0]==NULL)
                return 0;
    if(nod->fiu[s[0]-'a']==NULL)
        return 0;
    return prefix(s+1,nod->fiu[s[0]-'a'])+1;
}

int Trie::cat(char* s, node* nod){
        if(nod == NULL)
                return 0;
            else
                if(s[0]==NULL)
                    return nod->nr_c;
                else
                    return cat(s+1,nod->fiu[s[0]-'a']);
}

int main()
{
    int cer;
    Trie trie;
    while(in>>cer>>sir){
        if(cer==0)
            trie.ins(sir);
        if(cer==1)
            trie.er(sir);
        if(cer==2)
            out<<trie.q_cate(sir)<<'\n'<<'\n';
        if(cer==3)
            out<<trie.q_pref(sir)<<'\n'<<'\n';

    }
    return 0;
}