Cod sursa(job #2878825)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 27 martie 2022 21:27:08
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back

#define dbg(x) cout << #x <<": " << x << "\n";
using ll = long long;

const string fn = "file";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");



const int SIGMA = 26;

class TrieNode{

public:
    int fr;
    int cnt;
    TrieNode *nxt[SIGMA];



    TrieNode(){
        fr = cnt = 0;
        for (int i = 0; i < SIGMA; ++i)
            nxt[i] = NULL;
    }


    void ins(char *w){
        if(*w == 0)
            this->cnt++;
        else{
            if(this->nxt[*w - 'a'] == NULL){
                this->nxt[*w - 'a'] = new TrieNode;
            }
            this->nxt[*w - 'a']->fr++;
            this->nxt[*w - 'a']->ins(w + 1);
        }
    }

    void del(char *w){
        if(*w == 0){
            this->cnt--;
        }
        else{
            this->nxt[*w - 'a']->fr--;
            this->nxt[*w - 'a']->del(w + 1);
        }
    }

    int nrap(char *w){
        if(*w == 0){
            return this->cnt;
        }
        else{
            if(this->nxt[*w - 'a'] == NULL)
                return 0;
            return this->nxt[*w - 'a']->nrap(w + 1);
        }
    }

    int lcp(char *w){
        if(*w == 0){
            return 0;
        }
        else{

            if(this->nxt[*w - 'a'] == NULL)
                return 0;

            if(this->nxt[*w-'a']->fr == 0)
                return 0;

            return  1 + this->nxt[*w - 'a']->lcp(w + 1);
        }
    }

};

class Trie{
public:
    TrieNode *root;
    Trie(){
        this->root = new TrieNode;
    }

    void ins(char *w){
        this->root->ins(w);
    }
    void del(char *w){
        this->root->del(w);
    }
    int nrap(char *w){
        return this->root->nrap(w);
    }
    int lcp(char *w){
        return this->root->lcp(w);
    }

};

Trie T;

int main(){

    int op;
    char s[100000];
    while(fin >> op >> s){
        if(op == 0)
            T.ins(s);
        else if(op == 1)
            T.del(s);
        else if(op == 2)
            fout << T.nrap(s) << '\n';
        else
            fout << T.lcp(s) << '\n';
    }


    return 0;
}