Cod sursa(job #1613047)

Utilizator mariapascuMaria Pascu mariapascu Data 25 februarie 2016 10:33:00
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
using namespace std;

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

const int L = 26;

struct Nod {
    Nod() {
        nrc = nrs = 0;
        for (int i = 0; i < L; i++)
            S[i] = 0;
    }

    int nrc, nrs;
    Nod *S[L];
};

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

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);

int main() {
    T = new Nod;
    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 fout << Prefix(T, s, 0) << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}

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

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

bool Delete(Nod *nod, char *s) {
    if (*s == 0) {
        nod->nrc--;
    }
    else if (Delete(nod->S[*s - 'a'], s + 1)) {
        nod->S[*s - 'a'] = 0;
        nod->nrc--;
    }
    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->S[*s - 'a'] == 0) {
        nod->S[*s - 'a'] = new Nod;
        nod->nrs++;
    }
    Insert(nod->S[*s - 'a'], s + 1);
}