Cod sursa(job #3274681)

Utilizator error500Ursaru Tudor Alexandru error500 Data 8 februarie 2025 09:51:43
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.14 kb
#include <string>
#include <fstream>
using namespace std;

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

class Trie {
    int cnt = 0; // Number of words ending at this Node
    int descendants = 0; // Number of words that depend on this node
    Trie *next[26] = {};

public:
    void insert(const string& str, int pos = 0) { // Insert str as a child of this
        descendants++;
        if (pos == int(str.size()))
            cnt++;
        else {
            if (!next[str[pos] - 'a'])
                next[str[pos] - 'a'] = new Trie;
            next[str[pos] - 'a']->insert(str, pos + 1);
        }
    }

    int count(const string& str, int pos = 0) {
        if (pos == int(str.size()))
            return cnt;
        if (!next[str[pos] - 'a'])
            return 0;
        return next[str[pos] - 'a']->count(str, pos + 1);
    }

    // Erases instance of str. Free all nodes that do not point to a word anymore
    void erase(const string& str, int pos = 0) {
        descendants--;
        if (pos == int(str.size()))
            cnt--;
        else {
            next[str[pos] - 'a']->erase(str, pos + 1);
            if (next[str[pos] - 'a']->descendants == 0) {
                delete next[str[pos] - 'a'];
                next[str[pos] - 'a'] = nullptr;
            }
        }
    }

    int lcp(const string& str, int pos = 0) { // Length of longest common prefix with str found in Trie
        if (pos == int(str.size()))
            return 0;
        if (!next[str[pos] - 'a'])
            return 0;
        return 1 + next[str[pos] - 'a']->lcp(str, pos + 1);
    }
};

#include <iostream>

int main() {
    Trie* trie = new Trie;
    int operatie;
    string cuv;
    while(in >> operatie >> cuv) {
        switch(operatie) {
        case 0:
            trie->insert(cuv);
            break;
        case 1:
            if(trie->count(cuv)) {
                trie->erase(cuv);
            }
            break;
        case 2:
            out << trie->count(cuv) << '\n';
            break;
        case 3:
            out << trie->lcp(cuv) << '\n';
            break;
        }
    }
}