Cod sursa(job #2202993)

Utilizator Anastasia11Susciuc Anastasia Anastasia11 Data 10 mai 2018 17:20:30
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <cstring>

using namespace std;

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

struct trie {
    int cnt;
    int nfii;

    trie* urm[30];

    trie() {
        cnt = nfii = 0;
        memset(urm, 0, sizeof(urm));
    }
};

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 Delete(trie *t, char *s) {
    if (*s == 0 && t -> cnt > 0) {
        t -> cnt--;
    } else if (t -> urm[*s-'a'] != 0 && Delete(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 apar(trie *t, char *s) {
    if (*s == 0)
        return t -> cnt;
    else if (t -> urm[*s - 'a'])
        return apar(t -> urm[*s-'a'], s+1);
    return 0;
}

int lung(trie *t, char *s, int K) {
    if (*s == 0 || t -> urm[*s - 'a'] == 0)
        return K;
    return lung(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') Delete(inc, s+2);
        else if (s[0] == '2') g << apar(inc, s+2) << '\n';
        else if (s[0] == '3') g << lung(inc, s+2, 0) << '\n';
    }

    return 0;
}