Cod sursa(job #2018656)

Utilizator EuAlexOtaku Hikikomori EuAlex Data 5 septembrie 2017 16:40:16
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <cstdio>
#include <algorithm>

using namespace std;

const int sigma = 26;
const int nmax = 20;

struct Trie {
    int term;
    int nf;
    Trie* fii[sigma];
};

Trie* root;
char str[1 + nmax];

void add(Trie* nod, char *s) {
    if(*s == '\0') {
        nod->term ++;
        return;
    }
    if(nod->fii[*s - 'a'] == NULL) {
        nod->fii[*s - 'a'] = new Trie();
        nod->nf ++;
    }
    add(nod->fii[*s - 'a'], s + 1);
}

bool del(Trie* nod, char *s) {
    if(*s == '\0') {
        nod->term --;
    } else if(del(nod->fii[*s - 'a'], s + 1)) {
        //delete nod->fii[*s - 'a'];
        nod->fii[*s - 'a'] = NULL;
        nod->nf --;
    }
    if(nod->term == 0 && nod->nf == 0 && nod != root) {
        delete nod;
        //nod = NULL;
        return 1;
    }
    return 0;
}

int apar(Trie* nod, char *s) {
    if(*s == '\0') {
        return nod->term;
    }
    if(nod->fii[*s - 'a'] == NULL) {
        return 0;
    }
    apar(nod->fii[*s - 'a'], s + 1);
}

int pref(Trie* nod, char *s, int h = 0) {
    if(*s == '\0' || nod->fii[*s - 'a'] == NULL) {
        return h;
    }
    pref(nod->fii[*s - 'a'], s + 1, h + 1);
}

int main() {
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    int n;
    root = new Trie();
    while(scanf("%d", &n) != EOF) {
        scanf("%s", &str);

        if(n == 0) {
            add(root, str);
        } else if(n == 1) {
            del(root, str);
        } else if(n == 2) {
            printf("%d\n", apar(root, str));
        } else {
            printf("%d\n", pref(root, str));
        }
    }

    return 0;
}