Cod sursa(job #2221540)

Utilizator stefan.botezStefan Botez stefan.botez Data 14 iulie 2018 18:21:10
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>

using namespace std;
class Trie
{
private:
    struct Node {
        int words;
        int nrsons;
        Node* sons[30];
        Node() {
            words = 0;
            nrsons = 0;
            for (int i = 0; i < 26; i++) {
                sons[i] = nullptr;
            }
        }
    };
    Node* root;
    bool del(Node* curr, string word, unsigned int index)
    {
        if(index == word.size())
        {
            curr->words--;
            return curr->nrsons == 0;
        }
        int c = word[index] - 'a';
        Node* node = curr->sons[c];
        bool ShouldDelete = del(node, word, index + 1);
        if(ShouldDelete)
        {
            Node* aux = curr->sons[c];
            curr->sons[c] = nullptr;
            delete aux;
            curr->nrsons--;
            return curr->nrsons == 0;
        }
        return 0;
    }
public:
    Trie(){root = new Node();}
    void add(string word)
    {
        Node* curr = root;
        for(unsigned int i = 0; i < word.size(); i++)
        {
            int c = word[i] - 'a';
            if(curr->sons[c] == nullptr)
            {
                curr->sons[c] = new Node();
            }
            curr->nrsons++;
            curr = curr->sons[c];
        }
        curr->words++;
    }
    void del(string word)
    {
        del(root, word, 0);
    }

    int cnt(string word)
    {
        Node* curr = root;
        for(unsigned int i = 0; i < word.size(); i++)
        {
            int c = word[i] - 'a';
            if(curr->sons[c] != nullptr)
                curr = curr->sons[c];
            else return 0;
        }
        return curr->words;
    }
    int prefix(string word)
    {
        int nr = 0;
        Node* curr = root;
        for(unsigned int i = 0; i < word.size(); i++)
        {
            int c = word[i] - 'a';
            if(curr->sons[c] != nullptr)
            {
                curr = curr->sons[c];
                nr++;
            }
            else
                return nr;
        }
        return nr;
    }
};
int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");
    Trie trie;
    int op;
    string s;
    while(f >> op >> s)
    {
        if(op == 0)
            trie.add(s);
        else if(op == 1)
            trie.del(s);
        else if(op == 2)
            g << trie.cnt(s) << endl;
        else
            g << trie.prefix(s) << endl;
    }
    return 0;
}