Cod sursa(job #3185605)

Utilizator HaulicaTudorHaulica Tudor HaulicaTudor Data 19 decembrie 2023 18:52:09
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>

using namespace std;

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

class Trie {
public:
    struct Node {
        int ct, frecv;
        Node *f[30];

        Node() : ct(0), frecv(0) {
            for (int i = 0; i < 30; ++i) {
                f[i] = nullptr;
            }
        }
    };

    Node *root;

    Trie() {
        root = new Node();
    }

    void add(char *s, Node *poz) {
        poz->ct++;
        if (*s == '\0') {
            poz->frecv++;
            return;
        }
        if (poz->f[*s - 'a'] == NULL) {
            poz->f[*s - 'a'] = new Node();
        }
        add(s + 1, poz->f[*s - 'a']);
    }

    void del(char *s, Node *poz) {
        poz->ct--;
        if (*s == '\0') {
            poz->frecv--;
            return;
        }
        del(s + 1, poz->f[*s - 'a']);
    }

    void Frecv(char *s, Node *poz) {
        if (*s == '\0') {
            fout << poz->frecv << '\n';
            return;
        }
        Frecv(s + 1, poz->f[*s - 'a']);
    }

    int LongestPrefix(char *s, Node *poz) {
        if (*s == '\0' || poz->f[*s - 'a'] == NULL || !poz->f[*s - 'a']->ct) {
            return 0;
        }
        return LongestPrefix(s + 1, poz->f[*s - 'a']) + 1;
    }
};

int main() {
    int op;
    char s[26];
    Trie t;
    while (fin >> op >> s) {
        if (op == 0) {
            t.add(s, t.root);
        } else if (op == 1) {
            t.del(s, t.root);
        } else if (op == 2) {
            t.Frecv(s, t.root);
        } else if (op == 3) {
            fout << t.LongestPrefix(s, t.root) << '\n';
        }
    }

    return 0;
}