Cod sursa(job #1622125)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 1 martie 2016 08:36:37
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>

using namespace std;

struct Trie
{
    int words;
    int prefixes;
    Trie *edges[26];
    Trie()
    {
        words = prefixes = 0;
        for (int i = 0; i < 26; i++)
            edges[i] = NULL;
    }
};

void addWord(int index, string &w, Trie *t)
{
    if (t->edges[w[index] - 'a'] == NULL)
        t->edges[w[index] - 'a'] = new Trie();

    t = t->edges[w[index] - 'a'];
    t->prefixes++;

    if (index == w.size() - 1)
        t->words++;
    else
        addWord(index + 1, w, t);
}

void deleteWord(int index, string &w, Trie *t)
{
    Trie *s = t->edges[w[index] - 'a'];
    s->prefixes--;

    if (index == w.size() - 1)
        s->words--;
    else
        deleteWord(index + 1, w, s);

    if (s->prefixes == 0)
    {
        delete s;
        t->edges[w[index] - 'a'] = NULL;
    }
}

int countWord(int index, string &w, Trie *t)
{
    t = t->edges[w[index] - 'a'];

    if (t == NULL)
        return 0;

    if (index == w.size() - 1)
        return t->words;
    else
        return countWord(index + 1, w, t);
}

int longestPrefix(int index, int depth, string &w, Trie *t)
{
    t = t->edges[w[index] - 'a'];

    if (t == NULL || t->prefixes == 0)
        return depth - 1;

    if (index != w.size() - 1 && t->prefixes >= 1)
        return longestPrefix(index + 1, depth + 1, w, t);

    return depth;
}

int main()
{
    int op;
    string w;

    ifstream f("trie.in");
    ofstream g("trie.out");
    Trie t;
    while (f >> op >> w)
    {
        if (op == 0)
            addWord(0, w, &t);
        else if (op == 1)
            deleteWord(0, w, &t);
        else if (op == 2)
            g << countWord(0, w, &t) << '\n';
        else if (op == 3)
            g << longestPrefix(0, 1, w, &t) << '\n';
    }
    f.close();
    g.close();

    return 0;
}