Cod sursa(job #2770658)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 22 august 2021 15:19:56
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <bits/stdc++.h>
#define NMAX 26

using namespace std;

struct Trie {
    int cnt;
    int ends;
    Trie *t[NMAX];
    Trie() {
        cnt = 0;
        for(int i = 0; i < NMAX; i++) {
            ends = 0;
            t[i] = NULL;
        }
    }
    void add(const char *w) {
        cnt ++;
        if(w[0] == '\0') {
            ends ++;
            return ;
        }
        int idx = w[0] - 'a';
        if(this->t[idx] == NULL) {
            this->t[idx] = new Trie();
        }
        this->t[idx]->add(w+1);
    }
    void del(const char *w) {
        cnt --;
        if(w[0] == '\0') {
            ends --;
            return ;
        }
        int idx = w[0] - 'a';
        this->t[idx]->del(w+1);
        if(this->t[idx]->cnt == 0) {
            delete this->t[idx];
            this->t[idx] = NULL;
        }
    }
    int count(const char *w) {
        if(w[0] == '\0') {
            return this->ends;
        }
        int idx = w[0] - 'a';
        if(this->t[idx] == NULL) {
            return 0;
        }
        return this->t[idx]->count(w+1);
    }
    int longestPref(const char *w) {
        if(w[0] == '\0') {
                return 0;
        }
        int idx = w[0] -'a';
        if(this->t[idx] == NULL) {
            return 0;
        }
        return 1 + this->t[idx]->longestPref(w+1);
    }
};


int main()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    Trie *root = new Trie();
    int op;
    char w[23];
    while(scanf("%d %s",&op, w) != EOF) {
        if(op == 0) {
            root->add(w);
        }else if(op == 1) {
            root->del(w);
        }else if(op == 2) {
            printf("%d\n",root->count(w));
        }else {
            printf("%d\n",root->longestPref(w));
        }
    }

    return 0;
}