Cod sursa(job #3349129)

Utilizator iulia_morariuIuli Morariu iulia_morariu Data 25 martie 2026 17:08:11
Problema Trie Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.35 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <climits>
#include <vector>
#include <stack>
#include <cmath>
#include <queue>
// #include <bits/std++.h>
#define in  fin
#define out fout

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct node{
    int cnt; // cate is FIX eu
    node* nx[30];

    node(){
        cnt = 0;
        for(int i = 0; i < 30; i++) nx[i] = NULL;
    }
};

node* root = new node();

void add_cuvant(node* eu, string cuv, int it){
    // cout << "(ADD) cuv = " << cuv << " it = " << it << '\n';
    if(it == cuv.size()){
        eu->cnt++;
        return;
    }

    if(eu->nx[ cuv[it] - 'a' ] == NULL){
        eu->nx[ cuv[it] - 'a' ] = new node();
    }

    add_cuvant(eu->nx[ cuv[it] - 'a' ], cuv, it + 1);
}

bool elim_cuvant(node* eu, string cuv, int it){
    // cout << "(DEL) cuv = " << cuv << " it = " << it << '\n';
    if(it == cuv.size()){
        eu->cnt--;
        bool am_fii = 0;
        for(int i = 0; i < 30; i++){
            if(eu->nx[i] != NULL){ am_fii = 1; break; }
        }

        if(root != eu && !am_fii && eu->cnt == 0){
            delete eu;
            return 1;
        }
    }else if(elim_cuvant(eu->nx[ cuv[it] - 'a' ], cuv, it + 1)){

        eu->nx[cuv[it] - 'a'] = NULL;
        
        bool am_fii = 0;
        for(int i = 0; i < 30; i++){
            if(eu->nx[i] != NULL){ am_fii = 1; break; }
        }

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

int nr_ap(node* eu, string cuv, int it){
    if(it == cuv.size()){
        return eu->cnt;
    }

    if(eu->nx[ cuv[it] - 'a' ] == NULL){
        return 0;
    }
    return nr_ap(eu->nx[ cuv[it] - 'a' ], cuv, it + 1);
}

int pref_max(node* eu, string cuv, int it){
    // cout << "(PREF) cuv = " << cuv << " it = " << it << '\n';
    if(it != cuv.size() && eu->nx[ cuv[it] - 'a' ] != NULL){
        return pref_max(eu->nx[ cuv[it] - 'a' ], cuv, it + 1);
    }else{ return it; }
}

signed main(){
    ios_base::sync_with_stdio(false);
    in.tie(NULL);

    while(!fin.eof()){
        int x; string s; in >> x >> s;

        if(x == 0) add_cuvant(root, s, 0);
        else if(x == 1) elim_cuvant(root, s, 0);
        else if(x == 2) out << nr_ap(root, s, 0) << '\n';
        else if(x == 3) out << pref_max(root, s, 0) << '\n';
    }

    return 0;
}