Cod sursa(job #3233271)

Utilizator MirceaDonciuLicentaLicenta Mircea Donciu MirceaDonciuLicenta Data 2 iunie 2024 21:13:23
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.7 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>

using namespace std;

struct TrieNode {
    unordered_map<char, TrieNode*> children;
    int count;
    TrieNode() : count(0) {}
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    void insert(const string& word) {
        TrieNode* node = root;
        for (char ch : word) {
            if (node->children.find(ch) == node->children.end()) {
                node->children[ch] = new TrieNode();
            }
            node = node->children[ch];
        }
        node->count++;
    }

    void remove(const string& word) {
        removeHelper(root, word, 0);
    }

    int countOccurrences(const string& word) {
        TrieNode* node = root;
        for (char ch : word) {
            if (node->children.find(ch) == node->children.end()) {
                return 0;
            }
            node = node->children[ch];
        }
        return node->count;
    }

    int longestPrefix(const string& word) {
        TrieNode* node = root;
        int maxLength = 0, currentLength = 0;
        for (char ch : word) {
            if (node->children.find(ch) != node->children.end()) {
                currentLength++;
                node = node->children[ch];
                if (node->count > 0) {
                    maxLength = currentLength;
                }
            } else {
                break;
            }
        }
        return maxLength;
    }

private:
    TrieNode* root;

    bool removeHelper(TrieNode* node, const string& word, int depth) {
        if (!node) return false;

        if (depth == word.size()) {
            if (node->count > 0) {
                node->count--;
                return node->children.empty();
            }
            return false;
        }

        char ch = word[depth];
        if (removeHelper(node->children[ch], word, depth + 1)) {
            delete node->children[ch];
            node->children.erase(ch);
            return node->children.empty() && node->count == 0;
        }
        return false;
    }
};

int main() {
    ifstream infile("trie.in");
    ofstream outfile("trie.out");

    Trie trie;
    string command, word;

    while (infile >> command >> word) {
        if (command == "0") {
            trie.insert(word);
        } else if (command == "1") {
            trie.remove(word);
        } else if (command == "2") {
            outfile << trie.countOccurrences(word) << endl;
        } else if (command == "3") {
            outfile << trie.longestPrefix(word) << endl;
        }
    }

    infile.close();
    outfile.close();
    return 0;
}