Cod sursa(job #1638004)

Utilizator mariapascuMaria Pascu mariapascu Data 7 martie 2016 20:30:44
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct Nod {
    Nod() {
        for (int i = 0; i < 26; i++)
            f[i] = 0;
        nrc = nrs = 0;
    }
    int nrc, nrs;
    Nod * f[26];
};

Nod *T;
int k;
char s[25];

void Insert(Nod *nod, char *s);
bool Erase(Nod *nod, char *s);
int NrAp(Nod *nod, char *s);
int Prefix(Nod *nod, char *s, int k);

int main() {
    T = new Nod;
    while (fin >> k >> s)
        if (k == 0) Insert(T, s);
        else if (k == 1) Erase(T, s);
        else if (k == 2) fout << NrAp(T, s) << '\n';
        else fout << Prefix(T, s, 0) << '\n';
    fin.close();
    fout.close();
    return 0;
}

int Prefix(Nod *nod, char *s, int k) {
    if (*s == 0 || nod->f[*s - 'a'] == 0) return k;
    return Prefix(nod->f[*s - 'a'], s + 1, k + 1);
}

int NrAp(Nod *nod, char *s) {
    if (*s == 0) return nod->nrc;
    if (nod->f[*s - 'a'] != 0)
        return NrAp(nod->f[*s - 'a'], s + 1);
    return 0;
}

bool Erase(Nod *nod, char *s) {
    if (*s == 0) {
        nod->nrc--;
    }
    else if (Erase(nod->f[*s - 'a'], s + 1)) {
        nod->f[*s - 'a'] = 0;
        nod->nrs--;
    }
    if (nod->nrc == 0 && nod->nrs == 0 && nod != T) {
        delete nod;
        return true;
    }
    return false;

}

void Insert(Nod *nod, char *s) {
    if(*s == 0) {
        nod->nrc++;
        return;
    }
    if (nod->f[*s - 'a'] == 0) {
        nod->f[*s - 'a'] = new Nod;
        nod->nrs++;
    }
    Insert(nod->f[*s- 'a'], s + 1);
}