Cod sursa(job #2763762)

Utilizator DragosC1Dragos DragosC1 Data 16 iulie 2021 17:54:38
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
using namespace std;

struct Trie{
    int nr, nrcuv;
    Trie *lit[26];
    Trie() {
        nrcuv = nr = 0;
        for (int i = 0; i <= 25; i++)
            lit[i] = 0;
    }
};

Trie* root = new Trie();

void insert(Trie* nod, char s[]) {
    if (*s == '\0')
        nod->nrcuv++;
    else {
        int l = *s - 'a';
        if (nod->lit[l] == NULL) {
            nod->lit[l] = new Trie();
            nod->nr++;
        }
        insert(nod->lit[l], s + 1);
    }
}

bool Delete(Trie* nod, char s[]) {
    if (*s == '\0')
        nod->nrcuv--;
    else {
        int l = *s - 'a';
        if (Delete(nod->lit[l], s + 1)) {
            nod->lit[l] = NULL;
            nod->nr--;
        }
    }
    if (nod->nr == 0 && nod->nrcuv == 0 && nod != root) {
        delete nod;
        return 1;
    }
    return 0;
}

int search(Trie* nod, char s[]) {
    if (*s == '\0')
        return nod->nrcuv;
    else {
        int l = *s - 'a';
        if (nod->lit[l] != NULL)
            return search(nod->lit[l], s + 1);
    }
    return 0;
}   

int clpc(Trie* nod, char s[], int nr) {
    if (*s == '\0')
        return nr;
    else {
        int l = *s - 'a';
        if (nod->lit[l] != NULL)
           return clpc(nod->lit[l], s + 1, nr + 1);
    }
    return nr;
}

void solve() {
    int op; 
    char s[21];
    ifstream f("trie.in");
    ofstream g("trie.out");
    while (f >> op >> s) {
        if (op == 0)
            insert(root, s);
        else if (op == 1)
            Delete(root, s);
        else if (op == 2) 
            g << search(root, s) << '\n';
        else g << clpc(root, s, 0) << '\n';
    }
    f.close();
    g.close();
}

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