Cod sursa(job #3359671)

Utilizator Andrei_GAndreiG Andrei_G Data 1 iulie 2026 18:10:49
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 kb
#include <fstream>
#pragma GCC optimize("O3,unroll-loops")
#include <algorithm>
#include <cstring>
#include <climits>
#include <iomanip>
#include <numeric>
#include <bitset>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#define int long long
//#define int short
using namespace std;

ifstream cin("trie.in");
ofstream cout("trie.out");

const int nodemax = 2e6;
const int carmax = 26;

struct p{
    int to[carmax];
    int cntpre;
    int cntap;
}trie[nodemax + 5];

int nodes = 0;

void add(const string& s){
    int cur = 0;
    for (auto& c : s){
        int x = c - 'a';
        if (!trie[cur].to[x]){
            trie[cur].to[x] = ++nodes;
        }
        cur = trie[cur].to[x];
        trie[cur].cntpre++;
    }
    trie[cur].cntap++;
}

void erase(const string& s){
    int cur = 0;
    for (auto& c : s){
        int x = c - 'a';
        cur = trie[cur].to[x];
        trie[cur].cntpre--;
    }
    trie[cur].cntap--;
}

int aparitii(const string& s){
    int cur = 0;
    for (auto& c : s){
        int x = c - 'a';
        if (!trie[cur].to[x]){
            return 0;
        }
        cur = trie[cur].to[x];
    }
    return trie[cur].cntap;
}

int prefixmax(const string& s){
    int cur = 0, len = 0;
    for (auto& c : s){
        int x = c - 'a';
        if (!trie[cur].to[x]){
            break;
        }
        cur = trie[cur].to[x];
        if (!trie[cur].cntpre){
            break;
        }
        len++;
    }
    return len;
}

signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int op;
    string s;
    while(cin>>op){
        if (op == -1){
            break;
        }
        cin>>s;
        if (op == 0){
            add(s);
        }
        if (op == 1){
            erase(s);
        }
        if (op == 2){
            cout<<aparitii(s)<<"\n";
        }
        if (op == 3){
            cout<<prefixmax(s)<<"\n";
        }
    }
}