Cod sursa(job #2763768)

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

struct Trie {
    int nrcuv, nr;
    Trie* lit[26];
    Trie() {
        nrcuv = nr = 0;
        for (int i = 0; i < 26; 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] == 0) {
            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->nr--;
            nod->lit[l] = 0;
        }
    }
    if (nod->nrcuv == 0 && nod->nr == 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] != 0)
            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] != 0)
            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;
}