Cod sursa(job #3249245)

Utilizator StefantimStefan Timisescu Stefantim Data 15 octombrie 2024 17:26:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.48 kb
#include<bits/stdc++.h>
using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");
bool ok = 0;
struct Trie{
    struct Node{
        Node *c[27];
        int count;
        int leaves;
        Node()
        {
            count = leaves = 0;
            memset(c,0, sizeof(c));
        }
    };
    Node *root;
    Trie()
    {
        root = new Node;
    }
    Node* ret()
    {
        return root;
    }
    void insert(string s)
    {
        Node *node = root;
        for(auto &ch: s)
        {
            if(node -> c[int(ch - 'a')] == NULL)
            {
                node -> leaves++;
                node -> c[int(ch - 'a')] = new Node;
            }
            node = node -> c[int(ch - 'a')];
        }
        node -> count ++;
    }
    void del(Node *node, string s, int cnt)
    {
        if(cnt <= s.size() - 1)
            del(node -> c[int (s[cnt] - 'a')], s, cnt + 1);
        if(cnt == s.size())
        {
            node -> count--;
        }
        if(ok == 1)
        {
            node -> leaves--;
            node -> c[int(s[cnt] - 'a')] = NULL;
            ok = 0; 
        }
        if(node -> count == 0 && node -> leaves == 0 && node != ret())
        {
            ok = 1;
            delete node;
        }
    }

    void print(string s)
    {
        Node *node = root;
        for(auto &ch: s)
        {
            if(node -> c[int(ch - 'a')] == NULL)
            {
                fout << "0\n";
                return;
            }
            node = node -> c[int(ch - 'a')];
        }
        fout << node -> count << "\n";
    }

    void prefix(string s)
    {
        Node *node = root;
        int cnt = 0;
        for(auto &ch: s)
        {
            if(node -> c[int(ch - 'a')] == NULL)
                break;
            cnt++;
            node = node -> c[int(ch - 'a')];
        }
        fout << cnt << "\n";
    }
};
int main()
{
    int t;
    string s;
    Trie tr;
    try
    {
        while(fin >> t >> s)
        {
            switch (t)
            {
                case 0:
                    tr.insert(s);
                    break;
                case 1:
                    ok = 0;
                    tr.del(tr.ret(), s, 0);
                    break;
                case 2:
                    tr.print(s);
                    break;
                case 3:
                    tr.prefix(s);
                    break;
            }
        }
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
    
}