Cod sursa(job #2656851)

Utilizator AlexNeaguAlexandru AlexNeagu Data 8 octombrie 2020 21:56:07
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ll mod = 1e9 + 7;
ifstream in("trie.in");
ofstream out("trie.out");
const int N = 500005;
int child[N * 6][30];
int cnt[N * 6], is_leaf[N * 6];
int nxt = 1;

void add(string s) {
    int node = 0;
    for(int i = 0; i < s.size(); i++) {
        int w = s[i] - 'a';
        if(child[node][w] == 0) {
            child[node][w] = nxt++;
        }
        node = child[node][w];
        cnt[node]++;
    }
    is_leaf[node]++;;
}

void del(int pos, int node, string s) {
    
    if(pos == s.size() - 1) {
        int nxt_node = child[node][s[pos] - 'a'];
        cnt[nxt_node]--;
        is_leaf[nxt_node]--;
        if(!cnt[nxt_node]) {
            child[node][s[pos] - 'a'] = 0;
        }
        return;
    }

    int nxt_node = child[node][s[pos] - 'a'];
    
    del(pos + 1, nxt_node, s);
    cnt[nxt_node]--;
    is_leaf[nxt_node]--;
    if(!cnt[nxt_node]) {
        child[node][s[pos] - 'a'] = 0;
    }
}

int aps(string s) {
    int node = 0;
    for(int i = 0; i < s.size(); i++) {
        int w = s[i] - 'a';
        if(child[node][w] == 0) {
            return 0;
        }
        node = child[node][w];
    }
    return is_leaf[node];
}

int pre(string s) {
    int node = 0;
    int ans = 0;
    for(int i = 0; i < s.size(); i++) {
        int w = s[i] - 'a';
        if(child[node][w] == 0) {
            break;
        }
        node = child[node][w];
        ans++;
    }
    return ans;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int op;
    string s;
    while(in >> op >> s) {
        if(op == 0) {
            add(s);
        } else if(op == 1) {
            del(0, 0, s);
        } else if(op == 2) {
            out << aps(s) << '\n';
        } else {
            out << pre(s) << '\n';
        }
    }
    return 0;
}