Cod sursa(job #2702555)

Utilizator richardbaczur1Baczur Richard richardbaczur1 Data 4 februarie 2021 17:45:30
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.51 kb
#include <bits/stdc++.h>
#define BUFF_SIZE 32
#define infile "trie.in"
#define outfile "trie.out"

using namespace std;

struct TrieNode
{
    int cnt, c_sons;
    TrieNode *next_nodes[26];

    TrieNode() {
        cnt = 0;
        c_sons = 0;
        memset(next_nodes, 0, sizeof(next_nodes));
    }
};

TrieNode *root = new TrieNode;

void insert_word(TrieNode *root, const char *s)
{
    if (*s == '\n')
    {
        root->cnt++;
        return;
    }

    int idx = (int) (*s - 'a');
    if (!root->next_nodes[idx])
    {
        root->next_nodes[idx] = new TrieNode;
        root->c_sons++;
    }

    insert_word(root->next_nodes[idx], s + 1);
}

int delete_word(TrieNode *root, const char *s)
{
    int idx = (int) (*s - 'a');
    if (*s == '\n')
    {
        root->cnt--;
    }
    else if (delete_word(root->next_nodes[idx], s + 1))
    {
        root->next_nodes[idx] = 0;
        root->c_sons--;
    }

    // Message for those who check out this solution, I know it took me some time to grasp this concept :))
    // root != ::root checks whether the root inside the function is equal to the root of the entire structure
    if (root->cnt == 0 && root->c_sons == 0 && root != ::root)
    {
        delete root;
        return 1;
    }

    return 0;
}

int query(TrieNode *root, const char *s)
{
    if (*s == '\n')
        return root->cnt;

    int idx = (int) (*s - 'a');
    if (root->next_nodes[idx] != 0)
    {
        return query(root->next_nodes[idx], s + 1);
    }
}

int largest_prefix(TrieNode *root, const char *s, unsigned int k)
{
    int idx = (int) (*s - 'a');
    if (*s == '\n' || root->next_nodes[idx] == 0)
    {
        return k;
    }
    return largest_prefix(root->next_nodes[idx], s + 1, k + 1);
}

int main()
{
    freopen(infile, "r", stdin);
    freopen(outfile, "w", stdout);

    char* word;
    word = (char*) malloc(BUFF_SIZE);

    fgets(word, 32, stdin);
    while (!feof(stdin))
    {
        const char op = word[0];
        if (op == '0')
        {
            insert_word(root, word + 2);
        }
        else if (op == '1')
        {
            delete_word(root, word + 2);
        }
        else if (op == '2')
        {
            printf("%d\n", query(root, word + 2));
        }
        else if (op == '3')
        {
            printf("%d\n", largest_prefix(root, word + 2, 0));
        }
        fgets(word, 32, stdin);
    }

    fclose(stdin);
    fclose(stdout);
    return 0;
}