Cod sursa(job #2146607)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 28 februarie 2018 08:36:34
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <cstring>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

struct trie {
    int nfii, cnt;
    trie *urm[30];
    trie() {
        nfii = cnt = 0;
        memset(urm, 0, sizeof(urm));
    }
};
trie *inc = new trie;
char s[30];

void add(trie *t, char *s) {
    int c;
    while (*s) {
        c = *s-'a';
        if (t -> urm[c] == 0)
            t -> urm[c] = new trie, t -> nfii++;
        t = t -> urm[c];
        s++;
    }
    t -> cnt++;
}

bool _delete(trie *t, char *s) {
    if (*s == 0 && t -> cnt > 0) t -> cnt--;
    if (t -> cnt == 0 && t -> nfii == 0) {
        delete t;
        return 1;
    } else if (t -> urm[*s-'a'] && _delete(t -> urm[*s-'a'], s+1))
        t -> urm[*s-'a'] = 0, t -> nfii--;
    return 0;
}

int cer1(trie *t, char *s) {
    if (*s == 0) return t -> cnt;
    if (t -> urm[*s-'a']) return cer1(t->urm[*s-'a'], s+1);
    return 0;
}

int cer2(trie *t, char *s, int K) {
    if (t -> urm[*s-'a'] == 0 || *s == 0)
        return K;
    return cer2(t -> urm[*s-'a'], s+1, K+1);
}

int main() {
    while (f.getline(s, sizeof(s))) {
        if (s[0] == '0') add(inc, s+2);
        else if (s[0] == '1') _delete(inc, s+2);
        else if (s[0] == '2') g << cer1(inc, s+2) << '\n';
        else g << cer2(inc, s+2, 0) << '\n';
    }
    return 0;
}