Cod sursa(job #2622504)

Utilizator bem.andreiIceman bem.andrei Data 1 iunie 2020 13:46:22
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>

using namespace std;
ifstream r("trie.in");
ofstream w("trie.out");
class trie
{
    int ult, cuv;
    trie*edg[26];
public:
    trie(int a=0){
        ult=a;
        cuv=a;
        memset(edg, 0, sizeof(edg));
    }
    void push(const string &s,const int &pos=0){
        if(s[pos]==0){
            ult++;
            cuv++;
            return;
        }
        if(edg[s[pos]-'a']==nullptr){
            edg[s[pos]-'a']=new trie;
        }
        edg[s[pos]-'a']->push(s, pos+1);
        cuv++;
    }
    void pop(const string &s,const int &pos=0){
        if(s[pos]==0){
            ult--;
            cuv--;
            return;
        }
        edg[s[pos]-'a']->pop(s, pos+1);
        cuv--;
    }
    int aparitii(const string &s,const int &pos=0){
        if(s[pos]==0){
            return ult;
        }
        if(edg[s[pos]-'a']==nullptr){
            return 0;
        }
        return edg[s[pos]-'a']->aparitii(s, pos+1);
    }
    int pref(const string &s,const int &pos=0){
        if(cuv==0){
            return pos-1;
        }
        if(s[pos]==0){
            return pos;
        }
        if(edg[s[pos]-'a']==nullptr){
            return pos;
        }
        return edg[s[pos]-'a']->pref(s, pos+1);
    }
};
trie *root= new trie;
int main()
{
    int t;
    string s;
    while(r>>t>>s)
    {
        if(t==0)
        {
            root->push(s, 0);
        }
        if(t==1)
        {
            root->pop(s, 0);
        }
        if(t==2)
        {
            w<<root->aparitii(s, 0)<<"\n";
        }
        if(t==3)
        {
            w<<root->pref(s, 0)<<"\n";
        }
    }
    return 0;
}