Cod sursa(job #3036687)

Utilizator mihaistamatescuMihai Stamatescu mihaistamatescu Data 24 martie 2023 20:21:43
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.26 kb
#include <fstream>

using namespace std;

struct node {
    int value;
    int nrC;
    node *next[26]{};

    node() {
        for (auto &i: next) {
            i = NULL;
        }
        value = 0;
        nrC = 0;
    }
};

node *root;

void insertWord(char *c, node *currentNode) {
    if (*c != 0) {
        if (currentNode->next[*c - 'a'] == NULL) {
            currentNode->next[*c - 'a'] = new node;
            currentNode->nrC++;
        }
        insertWord(c + 1, currentNode->next[*c - 'a']);
        return;
    }
    currentNode->value++;
}

int countWord(char *c, node *currentNode) {
    if (*c != 0) {
        if (currentNode->next[*c - 'a'] == NULL) {
            return 0;
        }
        return countWord(c + 1, currentNode->next[*c - 'a']);
    }
    return currentNode->value;
}

void deleteWord(char *c, node *currentNode) {
    if (*c != 0) {
        if (currentNode->next[*c - 'a'] == NULL) {
            return;
        }
        deleteWord(c + 1, currentNode->next[*c - 'a']);
        if (currentNode->next[*c - 'a']->value == 0 && currentNode->next[*c - 'a']->nrC == 0) {
            delete currentNode->next[*c - 'a'];
            currentNode->next[*c - 'a'] = NULL;
            currentNode->nrC--;
        }
        return;
    }
    currentNode->value--;
}

int longestPrefix(char *c, node *currentNode) {
    if (*c != 0) {
        if (currentNode->next[*c - 'a'] == NULL) {
            return 0;
        }
        return 1 + longestPrefix(c + 1, currentNode->next[*c - 'a']);
    }
    return 0;
}

void deleteTrie(node *currentNode) {
    if (currentNode == NULL) {
        return;
    }
    for (auto &i: currentNode->next) {
        if (i != NULL) {
            deleteTrie(i);
        }
    }
    delete currentNode;
}

int op;
char w[22];

int main() {
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    root = new node;
    while (fin >> op >> w) {
        switch (op) {
            case 0:
                insertWord(w, root);
                break;
            case 1:
                deleteWord(w, root);
                break;
            case 2:
                fout << countWord(w, root) << "\n";
                break;
            case 3:
                fout << longestPrefix(w, root) << "\n";
                break;
        }
    }
    return 0;
}