Cod sursa(job #3352017)

Utilizator RosaSofianRosa Sofian RosaSofian Data 23 aprilie 2026 09:23:15
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 kb
#include <bits/stdc++.h>
using namespace std;

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

struct TRIE {
    vector<int> next;
    int pref, end;
    TRIE() {
        next = vector<int>(26, -1);
        pref = end = 0;
    }
};

string s;
vector<TRIE> trie;

void insert() {
    int u = 0;
    trie[u].pref++;

    for (char ch : s) {
        int c = ch - 'a';

        if (trie[u].next[c] == -1) {
            trie[u].next[c] = trie.size();
            trie.push_back(TRIE());
        }

        u = trie[u].next[c];
        trie[u].pref++;
    }

    trie[u].end++;
}

void erase() {
    int u = 0;

    // verificăm dacă există
    for (char ch : s) {
        int c = ch - 'a';
        if (trie[u].next[c] == -1)
            return; // nu există
        u = trie[u].next[c];
    }

    if (trie[u].end == 0) return;

    // scădem
    u = 0;
    trie[u].pref--;

    for (char ch : s) {
        int c = ch - 'a';
        u = trie[u].next[c];
        trie[u].pref--;
    }

    trie[u].end--;
}

int cate_cuv_s() {
    int u = 0;

    for (char ch : s) {
        int c = ch - 'a';

        if (trie[u].next[c] == -1)
            return 0;

        u = trie[u].next[c];
    }

    return trie[u].end;
}

int cel_mai_lung_prefix() {
    int u = 0, cnt = 0;

    for (char ch : s) {
        int c = ch - 'a';

        if (trie[u].next[c] == -1)
            break;

        u = trie[u].next[c];

        if (trie[u].pref == 0)
            break;

        cnt++;
    }

    return cnt;
}

int main() {
    trie.push_back(TRIE()); // 🔥 ROOT (foarte important)

    int nr;
    while (fin >> nr >> s) {
        if (nr == 0) {
            insert();
        } else if (nr == 1) {
            erase();
        } else if (nr == 2) {
            fout << cate_cuv_s() << '\n';
        } else {
            fout << cel_mai_lung_prefix() << '\n';
        }
    }

    return 0;
}