Cod sursa(job #3353109)

Utilizator mitoceanuci@gmail.comMitoceanu Ciprian [email protected] Data 4 mai 2026 19:49:01
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.53 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

class TrieNode{
public:
    int wordCount;   
    int prefixCount; 
    TrieNode* children[26];

    TrieNode() {
        wordCount = 0;
        prefixCount = 0;
        for (int i = 0; i < 26; i++) {
            children[i] = nullptr;
        }
    }
};

class TRIE{
private:
     TrieNode* root;
public:
    TRIE() { root = new TrieNode(); }

    void insert(string word)
    {
        TrieNode* node = root;
        for (char c : word) {
            int index = c - 'a'; // TYPO CORECTAT AICI
            if (!node->children[index]) {
                node->children[index] = new TrieNode();
            }
            node = node->children[index];
            node->prefixCount++; // Încă un cuvânt folosește acest prefix
        }
        node->wordCount++;
    }
    
    void erase(string word)
    {
        TrieNode* node = root;
        for (char c : word) {
            int index = c - 'a';
            if (!node->children[index]) return; 
            
            node = node->children[index];
            node->prefixCount--; 
        }
        node->wordCount--;
    }

    int count(string word)
    {
        TrieNode* node = root;
        for (char c : word) {
            int index = c - 'a';
            if (!node->children[index] || node->children[index]->prefixCount == 0) {
                return 0; 
            }
            node = node->children[index];
        }
        return node->wordCount;
    }

    int longest_prefix(string word)
    {
        TrieNode* node = root;
        int length = 0;
        
        for (char c : word) {
            int index = c - 'a';
            if (!node->children[index] || node->children[index]->prefixCount == 0) {
                break;
            }
            node = node->children[index];
            length++; 
        }
        
        return length;
    }
};

int main()
{
    
    ifstream cin("trie.in");
    ofstream cout("trie.out");
    
    
    TRIE trie;
    int op;
    string word;
    
    while(cin>>op>>word)
    {
        switch (op)
        {
        case 0:
            trie.insert(word);
            break;
        case 1:
            trie.erase(word);
            break;
        case 2:
            cout<<trie.count(word)<<endl;
            break;
        case 3:
            cout<<trie.longest_prefix(word)<<endl;
            break;
        default:
            break;
        }
    }
    return 0;
}