Cod sursa(job #3338101)

Utilizator ONLYGODYBochis Andrei ONLYGODY Data 31 ianuarie 2026 14:00:57
Problema Trie Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <bits/stdc++.h>
using namespace std;

#define ll int
#define ull unsigned ll
#define cll const ll
#define nl '\n'
#define sp ' '
#define pb push_back
#define mp make_pair
#define vec vector

// #define fi cin
// #define fo cout

#define FILENAME string("trie")
fstream fi (FILENAME + ".in", ios::in);
fstream fo (FILENAME + ".out", ios::out);
#define INF 2147483647

void solve();
void add(char[], cll);
void myDelete(char[], cll);
void showCount(char[], cll);
void query3(char[], cll, cll);

struct node{

    char val;
    ll count;
    ll finalCount;
    ll pos[26];
};

vector<node> tree;

int main() {

    solve();
    return 0;
}

void solve() {

    ll q;
    tree.push_back({'0', 0, 0, {}});

    while(fi >> q){

        char w[21];
        fi >> w;

        if (q == 0)
            add(w, 0);

        if (q == 1)
            myDelete(w, 0);

        if (q == 2)
            showCount(w, 0);

        if (q == 3)
            query3(w, 0, 0);
    }
    return void();
}

void add(char w[], cll node){

    cll nextChild = tree[node].pos[w[0] - 'a'];

    if (node)
        ++tree[node].count;

    if(w[0] == '\0') {

        ++tree[node].finalCount;
        return;
    }

    if(nextChild){
        
        add(w + 1, nextChild);
    }
    else{
        
        tree.push_back({w[0], 0, 0, {}});
        tree[node].pos[w[0] - 'a'] = tree.size() - 1;
        add(w + 1, tree.size() - 1);
    }
}

void myDelete(char w[], cll node){

    cll nextChild = tree[node].pos[w[0] - 'a'];

    if (node && tree[node].count)
        --tree[node].count;

    if(w[0] == '\0' && tree[node].finalCount) {
        
        --tree[node].finalCount;
        return;
    }

    if (nextChild)
        myDelete(w + 1, nextChild);
}

void showCount(char w[], cll node){

    cll nextChild = tree[node].pos[w[0] - 'a'];

    if (w[0] == '\0'){
        
        fo << tree[node].finalCount << nl;
        return;
    }
    
    if(nextChild == 0){
        
        fo << 0 << nl;
        return;
    }
    
    showCount(w + 1, nextChild);
}

void query3(char w[], cll node, cll depth){

    cll nextChild = tree[node].pos[w[0] - 'a'];
    
    if(w[0] == '\0'){
        
        fo << depth << nl;
        return;
    }
    
    if(nextChild && tree[nextChild].count)
        query3(w + 1, nextChild, depth + 1);
    else{
        
        fo << depth << nl;
        return;
    }
}