Cod sursa(job #2660625)

Utilizator vladth11Vlad Haivas vladth11 Data 19 octombrie 2020 21:30:07
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#include <bits/stdc++.h>
#define debug(x) cerr << #x << " " << x << "\n"
#define debug_with_space(x) cerr << #x << " " << x << " "


using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, pii> piii;

const ll NMAX = 100001;
const ll INF = (1LL << 50);
const ll MOD = 1000000007;
const ll BLOCK = 101;
const ll nr_of_bits = 18;

class Trie{
    struct Node{
        int ap;
        int sf;
        Node* v[26];
        Node(){
            ap = 0;
            sf = 0;
            for(int i = 0; i < 26; i++){
                v[i] = NULL;
            }
        }
    };
    void add(Node* &node, string s, int k, int val){
        if(node == NULL){
            node = new Node();
        }
        node->ap += val;
        if(k == s.size()){
            node->sf+=val;
            return ;
        }
        int poz = s[k] - 'a';
        add(node->v[poz], s, k + 1, val);
    }
    int nr_ap(Node* &node, string s, int k){
        if(node == NULL){
            return 0;
        }
        if(k == s.size()){
            return node->sf;
        }
        int poz = s[k] - 'a';
        return nr_ap(node->v[poz], s, k + 1);
    }
    int lgpref(Node* &node, string s, int k){
        if(node == NULL){
            return k - 1;
        }
        if(node->ap == 0){
            return k - 1;
        }
        if(k == s.size())
            return k;
        int poz = s[k] - 'a';
        return lgpref(node->v[poz], s, k + 1);
    }
    Node* root;
public:
    int count(string s){
        return nr_ap(root, s, 0);
    }
    void insert(string s){
        add(root, s, 0, 1);
    }
    void erase(string s){
        add(root, s, 0, -1);
    }
    int lp(string s){
        return lgpref(root, s, 0);
    }
}trie;

int main() {
    ifstream cin("trie.in");
    ofstream cout("trie.out");
    int c;
    string s;
    int cnt = 0;
    while(cin >> c && cin >> s){
        if(c == 0){
            trie.insert(s);
        }else if(c == 1){
            trie.erase(s);
        }else if(c == 2){
            cnt++;
            cout << trie.count(s) << "\n";
        }else{
            cout << trie.lp(s) << "\n";
        }
    }
}