Cod sursa(job #2926770)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 18 octombrie 2022 17:59:21
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;

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

class TrieNode
{
public:
    TrieNode()
    {
        memset(nodes, 0, sizeof(nodes));
        frv = 0;
    }

    void Insert(string& str, int depth = 0)
    {
        subTree++;
        if (depth == str.size())
        {
            frv++;
            return;
        }

        int index = str[depth] - 'a';
        if (nodes[index] == nullptr)
        {
            nodes[ index] = new TrieNode();
        }
        nodes[index]->Insert(str, depth + 1);
    }

    void Delete(string& str, int depth = 0)
    {
        subTree--;
        if (depth == str.size())
        {
            frv--;
            return;
        }

        int index = str[depth] - 'a';
        nodes[index]->Delete(str, depth + 1);
    }
    
    int GetFrv(string& str, int depth = 0)
    {
        int index = str[depth] - 'a';

        if (depth == str.size())
        {
            return frv;
        }
        if (nodes[index] == nullptr) 
        {
            return 0;
        }
        return nodes[index]->GetFrv(str, depth + 1);
    }

    int GetPrefixLen(string& str, int depth = 0)
    {
        if (subTree == 0 && depth == 0) 
        {
            return 0;
        }
        if (subTree == 0)
        {
            return depth - 1;
        }
        if (depth >= str.size()) {
            return depth;
        }

        int index = str[depth] - 'a';
        if (nodes[index] == nullptr)
        {
            return depth;   
        }
        return nodes[index]->GetPrefixLen(str, depth + 1);
    }

private:
    TrieNode* nodes[26];
    int frv = 0;
    int subTree = 0;
};


int main()
{
    int task;
    string str;
    TrieNode firstNode;
    int i = 0;
    while (fin >> task >> str)
    {
        cout << task << endl;
        if (task == 0)
        {
            firstNode.Insert(str);
        }
        else if (task == 1)
        {
            firstNode.Delete(str);
        }
        else if (task == 2)
        {
            fout << firstNode.GetFrv(str) << '\n';
        }
        else if (task == 3)
        {
            fout << firstNode.GetPrefixLen(str) << '\n';
        }
    }
}