Cod sursa(job #2653720)

Utilizator alexandru021Alexandru Gabriel alexandru021 Data 28 septembrie 2020 21:28:26
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.61 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

string name = "trie";
ifstream fin(name + ".in");
ofstream fout(name + ".out");

const int SIGMA = 26;

struct TrieNode {
    TrieNode* fii[SIGMA] = {};
    int nrFii = 0;
    int nrCuvinte = 0;
};

TrieNode *root;

void adaugaCuvant(TrieNode *node, string cuvant) {
    if (cuvant.size() == 0) {
        /// nod terminal - daca ramanem fara litere
        /// inseamna ca nodul actual simbolizeaza sfarsitul cuvantului
        ++node->nrCuvinte;
        return;
    }

    int pos = cuvant[0] - 'a';
    if (node->fii[pos] == nullptr) {
        node->fii[pos] = new TrieNode;
        ++node->nrFii;
    }
    /// mergem in nodul corespondent primei litere din cuvant
    /// cu cuvantul fara prima litera
    adaugaCuvant(node->fii[pos], cuvant.substr(1));
}

int nrAparitiiCuvant(TrieNode* node, string cuvant) {
    if (node == nullptr) {
        return 0;
    }
    if (cuvant.size() == 0) {
        return node->nrCuvinte;
    }
    int pos = cuvant[0] - 'a';
    string cuvantNou = cuvant.substr(1);
    return nrAparitiiCuvant(node->fii[pos], cuvantNou);
}

int lungimePrefix(TrieNode* node, string cuvant) {
    if (cuvant.size() == 0) {
        return 0;
    }

    int pos = cuvant[0] - 'a';
    if (node->fii[pos] == nullptr) {
        return 0;
    }
    string cuvantNou = cuvant.substr(1);
    return 1 + lungimePrefix(node->fii[pos], cuvantNou);
}



void stergeCuvant(TrieNode* node, string cuvant){
    //crtNode->wordsContained --;
    if(cuvant.size() == 0){
        node->nrCuvinte --;
        return;
    }
    int nextIndex = cuvant[0] - 'a';
    stergeCuvant(node->fii[nextIndex], cuvant.substr(1));
    if(node->fii[nextIndex]->nrFii == 0){
        --node->nrFii;
        free(node->fii[nextIndex]);
        node->fii[nextIndex] = NULL;
    }
}


void dezalocaTrie(TrieNode* node) {
    if (node == nullptr) {
        return;
    }
    for (int i = 0; i < SIGMA; ++i) {
        dezalocaTrie(node->fii[i]);
    }
    delete node;
}

int main()
{
    int op;
    string s;


    while (fin >> op >> s) {
        if (root == nullptr) {
            root = new TrieNode;
        }
        if (op == 0) {
            adaugaCuvant(root, s);
        }
        else if (op == 1) {
            stergeCuvant(root, s);
        }
        else if (op == 2) {
            fout << nrAparitiiCuvant(root, s) << '\n';
        }
        else if (op == 3) {
            fout << lungimePrefix(root, s) << '\n';
        }
    }
    dezalocaTrie(root);
    return 0;
}