Cod sursa(job #3359566)

Utilizator pkseVlad Bondoc pkse Data 30 iunie 2026 13:19:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <bits/stdc++.h>
using namespace std;

const int cmax = 27;

struct trie {
    struct node {
        int cnt = 0, cnts = 0;
        node* sub[cmax]{};
        ~node() { del(); }
        void del() {
            for(auto &i : sub) if(i) delete i, i = nullptr;
        }
    };

    node *r = new node;

    int find(string &s) {
        node *n = r;
        for(int i = 0; i < s.size(); i ++) {
            int ch = s[i] - 'a';
            if(!n->sub[ch] || !n->sub[ch]->cnt) return 0;
            n = n->sub[ch];
        }
        return n->cnts;
    }

    int find2(string &s) {
        node *n = r;
        for(int i = 0; i < s.size(); i ++) {
            int ch = s[i] - 'a';
            if(!n->sub[ch] || !n->sub[ch]->cnt) return i;
            n = n->sub[ch];
        }
        return s.size();
    }

    void insert(string &s) {
        node *n = r; n->cnt ++;
        for(int i = 0; i < s.size(); i ++) {
            int ch = s[i] - 'a';
            if(!n->sub[ch] || !n->sub[ch]->cnt) n->sub[ch] = new node;
            n = n->sub[ch];
            n->cnt ++;
        }
        n->cnts ++;
    }

    void remove(string &s) {
        node *n = r;
        for(int i = 0; i < s.size() && n->cnt; i ++) {
            int ch = s[i] - 'a';
            if(!n->sub[ch] || !n->sub[ch]->cnt) assert(false);
            n = n->sub[ch];
            n->cnt --;
        }
        if(n->cnt)
            n->cnts --;
        else
            n->del();
    }
};

int main() {
    ifstream cin("trie.in");
    ofstream cout("trie.out");
    cin.tie(0)->sync_with_stdio(0);
    trie str;
    int t;
    string s;
    while(cin >> t >> s) {
        if(t == 0) {
            str.insert(s);
        } else if(t == 1) {
            str.remove(s);
        } else if(t == 2) {
            cout << str.find(s) << '\n';
        } else {
            cout << str.find2(s) << '\n';
        }
    }
}