Cod sursa(job #1813447)

Utilizator PetrutiuPaulPetrutiu Paul Gabriel PetrutiuPaul Data 22 noiembrie 2016 23:06:22
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

struct node
{
    long long value = 0;
    long long nr_fii = 0;
    node *next[26] = {}; /// 26 characters in our alphabet
};

node *root = new node;

void addTrie(node *nd, char *w)
{
    if (*w == NULL) {
        nd->value++;
        return;
    }

    int nxt = *w - 'a';
    if (nd->next[nxt] == 0)
    {
        nd->nr_fii++;
        nd->next[nxt] = new node;
    }
    node* current = nd->next[nxt];
    addTrie(current, w+1);
}

bool removeTrie(node *nd, char *w)
{
    if (*w == '\0') {
        nd->value--;
    }
    else if (removeTrie(nd->next[*w - 'a'], w+1))
    {
        int nxt = *w - 'a';

        nd->next[nxt] = 0;
        nd->nr_fii--;
    }
    if (nd->nr_fii == 0 && nd->value == 0) {
        delete nd;
        return true;
        }
    return false;
}

int getTrie(node *nd, char *w)
{
    if (*w == '\0') {
        return nd->value;
    }

    int nxt = *w - 'a';
    if (nd->next[nxt] == '\0')
    {
        return 0;
    }

    node *current = nd->next[nxt];
    getTrie(current, w+1);
}

int queryTrie(node *nd, char *w, int k = 0)
{
    if (*w == '\0')
    {
        return k;
    }

    int nxt = *w - 'a';
    if (nd->next[nxt] == 0)
    {
        return k;
    }

    node *current = nd->next[nxt];
    return queryTrie(current, w+1, k+1);
}

int main()
{
    int op;
    char word[32];

    while(f>>op>>word)
    {

        if (op == 0)
        {
            addTrie(root, word);
        }
        else if (op == 1)
        {
            removeTrie(root, word);
        }
        else if (op == 2)
        {
            g << getTrie(root, word) << '\n';
        }
        else if (op == 3)
        {
            g << queryTrie(root, word) << '\n';
        }
    }

    return 0;
}