Cod sursa(job #1647829)

Utilizator radarobertRada Robert Gabriel radarobert Data 10 martie 2016 22:16:13
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <cstring>

using namespace std;

struct Trie
{
    int nrc;
    int counter;
    Trie *child[26];
    Trie()
    {
        nrc = counter = 0;
        memset(child, 0, sizeof(child));
    }
};

void add(Trie *node, char *s)
{
    if (*s == 0)
    {
        node->counter++;
        return;
    }
    if (node->child[*s - 'a'] == 0)
    {
        node->child[*s - 'a'] = new Trie;
        node->nrc++;
    }
    add(node->child[*s - 'a'], s+1);
}

void del(Trie *node, char *s)
{
    if (*s == 0)
    {
        node->counter--;
        return;
    }
    del(node->child[*s - 'a'], s+1);
    if (node->child[*s - 'a']->nrc == 0 && node->child[*s - 'a']->counter == 0)
    {
        delete node->child[*s - 'a'];
        node->child[*s - 'a'] = 0;
        node->nrc--;
    }
}

int query1(Trie *node, char *s)
{
    if (*s == 0)
        return node->counter;
    if (node->child[*s - 'a'] == 0)
        return 0;
    return query1(node->child[*s - 'a'], s+1);
}

int query2(Trie *node, char *s)
{
    if (*s == 0)
        return 0;
    if (node->child[*s - 'a'] == 0)
        return 0;
    if (node->nrc > 0)
        return 1 + query2(node->child[*s - 'a'], s+1);
    return 0;
}

int main()
{
    ifstream in("trie.in");
    ofstream out("trie.out");

    char w[22];
    int t;
    Trie *root = new Trie;
    while (in >> t)
    {
        in >> w;
        if (t == 0)
            add(root, w);
        else if (t == 1)
            del(root, w);
        else if (t == 2)
            out << query1(root, w) << '\n';
        else
            out << query2(root, w) << '\n';
    }

    return 0;
}