Cod sursa(job #3215805)

Utilizator PHOSSESSEDProsie Radu-Teodor PHOSSESSED Data 15 martie 2024 13:07:05
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include<iostream>
#include<vector>
#include<deque>
#include<queue>
#include<stack>
#include<set>
#include<unordered_map>
#include<map>
#include<unordered_set>
#include<ctime>
#include<random>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cassert>
#define fi first
#define se second
#define eb emplace_back
#define pb push_back
using namespace std;
using pii = pair<int,int>;
using ll = long long;
using ld = long double;

mt19937 rng(time(nullptr));

struct nod
{
    int cnt = 0, pass = 0;
    nod* next[26] = {nullptr};

    void baga(string &s,int p,int a)
    {
        pass += a;
        if(p==s.size()) cnt += a;
        else
            {   int l = s[p]-'a';
                if(!next[l]) next[l] = new nod;
                next[l]->baga(s,p+1,a);
            }

    }

    int lcp(string &s,int p)
    {
        if(s.size() == p) return 0;
        nod*& n = next[s[p]-'a'];
        if(n && n->pass) return 1 + n->lcp(s,p+1);
        return 0;
    }

    int ap(string &s,int p)
    {
        if(s.size() == p) return cnt;
        int l = s[p]-'a';
        return next[l] ? next[l]->ap(s,p+1) : 0;
    }
};

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);

    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);

    int t; string s; nod* trie = new nod;
    while(cin >> t >> s)
    {
        if(t==0 || t == 1)
            trie->baga(s,0,t==0?1:-1);
        else if(t == 3) cout << trie->lcp(s,0) << '\n';
        else cout << trie->ap(s,0) << '\n';

    }
}