Cod sursa(job #3152128)

Utilizator andiRTanasescu Andrei-Rares andiR Data 24 septembrie 2023 01:09:40
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <set>
#include <queue>
#include <stack>
#include <deque>
#include <iomanip>
#include <vector>
#include <bitset>

#pragma GCC optimize("O3")
#define fi first
#define se second
#define pb push_back
#define pf push_front

using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
typedef long long ll;
const ll Nmax=1e5+5, inf=1e9+5;
using pii=pair<int, int>;

struct TRIE{
    struct NODE{
        int val=0;
        int fin=0;
        NODE* nxt[26]={};
    };
    NODE* root;
    TRIE (){
        root=new NODE;
        root->val=1;
    }
    void add(string &s, int ind, NODE* crt){
        crt->val++;
        if (ind==s.size()){
            crt->fin++;
            return;
        }
        if (crt->nxt[s[ind]-'a']==0)
            crt->nxt[s[ind]-'a']=new NODE;
        add(s, ind+1, crt->nxt[s[ind]-'a']);
    }
    void del(string &s, int ind, NODE* crt){
         crt->val--;
        if (ind==s.size()){
            crt->fin--;
            return;
        }
        del(s, ind+1, crt->nxt[s[ind]-'a']);
    }
    int app(string &s, int ind, NODE* crt){
        if (ind==s.size())
            return crt->fin;
        if (crt->nxt[s[ind]-'a']==0)
            return 0;
        return app(s, ind+1, crt->nxt[s[ind]-'a']);
    }
    int pref(string &s, int ind, NODE* crt){
        if (crt->val==0)
            return ind-1;
        if (ind==s.size())
            return ind;
        if (crt->nxt[s[ind]-'a']==0)
            return ind;
        return pref(s, ind+1, crt->nxt[s[ind]-'a']);
    }
};
int main()
{
    char ch;
    string s;
    TRIE trie;
    while (fin>>ch){
        fin>>s;
        if (ch=='0')
            trie.add(s, 0, trie.root);
        else if (ch=='1')
            trie.del(s, 0, trie.root);
        else if (ch=='2')
            fout<<trie.app(s, 0, trie.root)<<'\n';
        else fout<<trie.pref(s, 0, trie.root)<<'\n';
    }
    return 0;
}