Cod sursa(job #1970047)

Utilizator mariapascuMaria Pascu mariapascu Data 18 aprilie 2017 20:28:23
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 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;
    }
    Nod *f[26];
    int nrc, nrs;
};

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

Nod *T;

int main() {
    T = new Nod;
    int k;
    char s[23];
    while (fin >> k >> s) {
        if (k == 0) Insert(T, s);
        else if (k == 1) Delete(T, s);
        else if (k == 2) fout << NrAp(T, s) << '\n';
        else if (k == 3) 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 Delete(Nod *nod, char *s) {
    if (*s == 0)
        nod->nrc--;
    else if (Delete(nod->f[*s - 'a'], s + 1)) {
        nod->nrs--;
        nod->f[*s - 'a'] = 0;
    }
    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);
}