Cod sursa(job #3351730)

Utilizator andreidumitrache1709andreidumitrache andreidumitrache1709 Data 21 aprilie 2026 10:19:39
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e5;
struct Node {
    int next[26] , cnt , pref;
};
struct Trie {
    Node t[MAXN + 1];
    int len = 1;
    void add( string s ) {
        int u = 1 , c;
        t[u].pref++;
        //cout << s << '\n';
        for( auto ch : s ) {
            c = ch - 'a';
            if( t[u].next[c] == 0 )
                t[u].next[c] = ++len;
            //cout << ch << ' ' << u << ' ' << t[u].next[c] << '\n';
            u = t[u].next[c];
            t[u].pref++;
        }
        t[u].cnt++;
    }
    void rem( string s ) {
        int u = 1 , c;
        t[u].pref--;
        for( auto ch : s ) {
            c = ch - 'a';
            u = t[u].next[c];
            t[u].pref--;
        }
        t[u].cnt--;
    }
    int countaparitii( string s ) {
        int u = 1 , c;
        for( auto ch : s ) {
            c = ch - 'a';
            if( !t[u].next[c] )
                return 0;
            u = t[u].next[c];
        }
        return t[u].cnt;
    }
    int prefixmax( string s ) {
        int u = 1 , cnt , c;
        cnt = 0;
        for( auto ch : s ) {
            c = ch - 'a';
            if( !t[u].next[c] )
                break;
            u = t[u].next[c];
            if( t[u].pref == 0 )
                break;
            cnt++;
        }
        return cnt;
    }
} trie;
int main() {
    ifstream cin( "trie.in" );
    ofstream cout( "trie.out" );
    int tip , q , i;
    string s;
    while( cin >> tip >> s ) {
        if( tip == 0 )
            trie.add( s );
        else if( tip == 1 )
            trie.rem( s );
        else if( tip == 2 )
            cout << trie.countaparitii( s ) << '\n';
        else
            cout << trie.prefixmax( s ) << '\n';
    }
    return 0;
}