Cod sursa(job #3281760)

Utilizator schema_227Stefan Nicola schema_227 Data 3 martie 2025 16:15:21
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

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

class TrieNode{
private:
    TrieNode* edg[26];
    int wordsEnded;
    int subtreeSize;
public:
    TrieNode(){
        memset(edg, 0, sizeof(edg));
        wordsEnded = 0;
        subtreeSize = 0;
    }
    void Add(const string &s, int depth = 0){
        subtreeSize++;
        if(depth == (int)s.size()){
            wordsEnded++;
            return;
        }
        int idx = s[depth] - 'a';
        if(!edg[idx]) edg[idx] = new TrieNode();
        edg[idx] -> Add(s, depth + 1);
    }
    void Remove(const string &s, int depth = 0){
        subtreeSize--;
        if(depth == (int)s.size()){
            wordsEnded--;
            return;
        }
        int idx = s[depth] - 'a';
        edg[idx] -> Remove(s, depth + 1);
        if(edg[idx] -> subtreeSize == 0){
            delete edg[idx];
            edg[idx] = 0;
        }
    }
    int Count(const string &s, int depth = 0){
        if(depth == (int)s.size()) return wordsEnded;
        int idx = s[depth] - 'a';
        if(!edg[idx]) return 0;
        return edg[idx] -> Count(s, depth + 1);
    }
    int Lcp(const string &s, int depth = 0){
        if(depth == (int)s.size()) return depth;
        int idx = s[depth] - 'a';
        if(!edg[idx]) return depth;
        return edg[idx] -> Lcp(s, depth + 1);
    }
};

int main(){
    TrieNode root;
    int op;
    string w;
    while(in >> op >> w){
        if(op == 0) root.Add(w);
        else if(op == 1) root.Remove(w);
        else if(op == 2) out << root.Count(w) << "\n";
        else if(op == 3) out << root.Lcp(w) << "\n";
    }
    return 0;
}