Cod sursa(job #3295060)

Utilizator EricDimiericdc EricDimi Data 1 mai 2025 23:06:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
/// https://infoarena.ro/problema/trie
#include <bits/stdc++.h>

using namespace std;

const int MAX_LEN = 1'000;
const int SIGMA = 26;

struct Trie {
    int cnt; /// numarul de cuvinte care se termina in subarborele curent
    int nrFii; /// numarul de fii ai nodului curent din trie
    Trie *fiu[SIGMA];
    Trie() {
        cnt = nrFii = 0;
        for (int i = 0; i < SIGMA; i++)
            fiu[i] = 0;
    }
};

Trie *root = new Trie;

void Insert(Trie *nod, char *s) {
    if (*s == '\n') {
        nod->cnt++;
        return;
    }
    if (nod->fiu[*s - 'a'] == 0) {
        nod->fiu[*s - 'a'] = new Trie;
        nod->nrFii++;
    }
    Insert(nod->fiu[*s - 'a'], s + 1);
}

int Delete(Trie *nod, char *s) {
    if (*s == '\n')
        nod->cnt--;
    else 
    if (Delete(nod->fiu[*s - 'a'], s + 1)) {
        nod->fiu[*s - 'a'] = 0;
        nod->nrFii--;
    }
    if (nod->cnt == 0 && nod->nrFii == 0 && nod != root) {
        delete nod;
        return 1;
    }
    return 0;
}

int Count(Trie *nod, char *s) {
    if (*s == '\n')
        return nod->cnt;
    if (nod->fiu[*s - 'a'])
        return Count(nod->fiu[*s - 'a'], s + 1);
    return 0;
}

int Lcp(Trie *nod, char *s, int k) {
    if (*s == '\n' || nod->fiu[*s - 'a'] == 0)
        return k;
    return Lcp(nod->fiu[*s - 'a'], s + 1, k + 1);
}

int main() {
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    
    char w[MAX_LEN];
    fgets(w, MAX_LEN, stdin);
    
    while (!feof(stdin)) {
        switch (w[0]) {
            case '0':
                Insert(root, w + 2);
                break;
            case '1':
                Delete(root, w + 2);
                break;
            case '2':
                cout << Count(root, w + 2) << "\n";
                break;
            case '3':
                cout << Lcp(root, w + 2, 0) << "\n";
                break;
        }
        fgets(w, MAX_LEN, stdin);
        //cout << op << " " << w << "\n";
    }
    
    fclose(stdin);
    fclose(stdout);
    return 0;
}