Cod sursa(job #3278326)

Utilizator jumaracosminJumara Cosmin-Mihai jumaracosmin Data 19 februarie 2025 13:09:28
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

std::ifstream fin("trie.in");
std::ofstream fout("trie.out");

const int SIZE = 2e5;
const int ALPHABET_SIZE = 26;

int trie[SIZE][ALPHABET_SIZE], isEnd[SIZE], frecv[SIZE], nodes = 1;

void Insert(std::string text) {
    int node = 0;
    for (char ch : text) {
        int idx = ch - 'a';
        if (!trie[node][idx]) trie[node][idx] = nodes++;
        node = trie[node][idx];
        frecv[node]++;
    }
    isEnd[node]++;
}

void Delete(std::string text) {
    int node = 0;
    for (char ch : text) {
        int idx = ch - 'a';
        node = trie[node][idx];
        frecv[node]--;
    }
    isEnd[node]--;
}

int Search(std::string text) {
    int node = 0;
    for (char ch : text) {
        int idx = ch - 'a';
        if (!trie[node][idx]) return 0;
        node = trie[node][idx];
    }
    return isEnd[node];
}

int LongestPrefix(std::string text) {
    int node = 0, len = 0;
    for (char ch : text) {
        int idx = ch - 'a';
        if (!trie[node][idx]) break;
        node = trie[node][idx];
        if (!frecv[node]) break;
        len++;
    }
    return len;
}

int main() {
    std::ios::sync_with_stdio(false);
    fin.tie(nullptr); fout.tie(nullptr);

    int op; std::string word;
    while (fin >> op >> word) {
        switch (op) {
            case 0: Insert(word); break;
            case 1: Delete(word); break;
            case 2: fout << Search(word) << "\n"; break;
            case 3: fout << LongestPrefix(word) << "\n"; break;
        }
    }
    return 0;
}