Cod sursa(job #2767437)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 6 august 2021 11:01:46
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>

using namespace std;

inline void Open(const string Name) {
    #ifndef ONLINE_JUDGE
        (void)!freopen((Name + ".in").c_str(), "r", stdin);
        (void)!freopen((Name + ".out").c_str(), "w", stdout);
    #endif
}

struct Trie {
    int cnt, nrfii;
    Trie *arr[26];

    Trie() {
        cnt = nrfii = 0;
        for(int i = 0;i <= 25;i++)
            arr[i] = 0;
    }
};

Trie *T = new Trie;

void insrt(Trie *root, char *str) {
    if(*str == '\0') {
        root -> cnt++;
        return;
    }

    if(root -> arr[(*str) - 'a'] == 0) {
        root -> arr[(*str) - 'a'] = new Trie;
        root -> nrfii++;
    }

    insrt(root -> arr[(*str) - 'a'], str + 1);
}

int delt(Trie *root, char *str) {
    if(*str == '\0')
        root -> cnt--;
    else if(delt(root -> arr[(*str) - 'a'], str + 1)) {
        root -> arr[(*str) - 'a'] = 0;
        root -> nrfii--;
    }

    if(root -> cnt == 0 && root -> nrfii == 0 && root != T) {
        delete root;
        return 1;
    }
    return 0;
}

int que(Trie *root, char *str) {
    if(*str == '\0')
        return root -> cnt;

    if(root -> arr[(*str) - 'a'])
        return que(root -> arr[(*str) - 'a'], str + 1);

    return 0;
}

int pre(Trie *root, char *str, int k) {
    if(*str == '\0' || root -> arr[(*str) - 'a'] == 0)
        return k;
    return pre(root -> arr[(*str) - 'a'], str + 1, k + 1);
}


int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    Open("trie");

    int op;
    char str[22];

    while(cin >> op >> str) {
        if(op == 0) insrt(T, str);
        if(op == 1) delt(T, str);
        if(op == 2) cout << que(T, str) << "\n";
        if(op == 3) cout << pre(T, str, 0) << "\n";
    }
    
    return 0;
}