Cod sursa(job #3351728)

Utilizator luca._.solosluca solos luca._.solos Data 21 aprilie 2026 10:19:22
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 26;

struct Node {
    int p, e;
    vector <int> next;

    Node() {
        p = 0;
        e = 0;
        next.assign(26, -1);
    }
};

struct Trie {
    vector <Node> t;

    Trie() {
        t.push_back(Node());
    }

    void add(string s) {
        int u = 0;
        t[u].p++;

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

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

            u = t[u].next[c];
            t[u].p++;
        }

        t[u].e++;
    }

    int count(string s) {
        int u = 0;

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

            if (t[u].next[c] == -1) {
                return 0;
            }

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

        return t[u].e;
    }

    int luuung(string s) {
        int u = 0, lg = 0;

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


            if (t[u].next[c] == -1) {
                return lg;
            }

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

            if (!t[u].p) {
                return lg;
            }
            lg++;

//            cout << ch << ' ' << t[u].p << '\n';
        }

        return lg;
    }

    bool erase(string s) {
        if (!count(s)) return 0;

        int u = 0;
        t[u].p--;

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

            u = t[u].next[c];
            t[u].p--;
        }

        t[u].e--;
        return 1;
    }
};

Trie trie;

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

    int tip;
    string s;

    while (fin >> tip >> s) {
        if (tip == 0) {
            trie.add(s);
        }
        else if (tip == 1) {
            trie.erase(s);
        }
        else if (tip == 2) {
            fout << trie.count(s) << '\n';
        }
        else {
            fout << trie.luuung(s) << '\n';
        }
    }

    return 0;
}