Cod sursa(job #2118786)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 31 ianuarie 2018 00:05:09
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <cstring>

using namespace std;

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

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

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

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

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

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

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