Cod sursa(job #2739589)

Utilizator DragosC1Dragos DragosC1 Data 8 aprilie 2021 21:45:24
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
#include <iostream>
using namespace std;

struct Trie {
    int nrCuv;
    int nrFii;
    Trie *Fiu[26];

    Trie() {
        nrCuv = nrFii = 0;
        for (int i = 0; i < 26; i++)
            Fiu[i] = NULL;
    }
};

Trie *T;

void Add(Trie *nod, char *s) {
    if (*s == '\0')
        nod->nrCuv++;
    else {
        int ind = *s - 'a';
        if (nod->Fiu[ind] == NULL) {
            nod->Fiu[ind] = new Trie();
            nod->nrFii++;
        }
        Add(nod->Fiu[ind], s + 1);
    }
}

bool Delete(Trie *nod, char *s) {
    if (*s == '\0')
        nod->nrCuv--;
    else {
        int ind = *s - 'a';
        if (Delete(nod->Fiu[ind], s + 1)) {
            nod->Fiu[ind] = NULL;
            nod->nrFii--;
        }
    }
    if (nod->nrCuv == 0 && nod->nrFii == 0 && nod != T) {
        delete nod;
        return 1;
    }
    return 0;
}

int Search(Trie *nod, char *s) {
    if (*s == '\0')
        return nod->nrCuv;
    int ind = *s - 'a';
    if (nod->Fiu[ind])
        return Search(nod->Fiu[ind], s + 1);
    return 0;
}

int Lcp(Trie *nod, char *s, int nr) {
    if (*s == '\0')
        return nr;
    int ind = *s - 'a';
    if (nod->Fiu[ind] == NULL)
        return nr;
    return Lcp(nod->Fiu[ind], s + 1, nr + 1);
}

void solve() {
    ifstream f("trie.in");
    ofstream g("trie.out");
    int op;
    char s[21];
    T = new Trie();
    while (f >> op >> s) {
        if (op == 0)
            Add(T, s);
        else if (op == 1)
            Delete(T, s);
        else if (op == 2) 
            g << Search(T, s) << '\n';
        else g << Lcp(T, s, 0) << '\n';
    }
    f.close();
    g.close();
}

int main() {
    solve();
    return 0;
}