Cod sursa(job #1843714)

Utilizator preda.andreiPreda Andrei preda.andrei Data 9 ianuarie 2017 10:13:02
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <map>
#include <string>

using namespace std;

struct Node
{
    int count = 0;
    map<char, Node*> sons;
};

void Insert(Node *t, const string &s)
{
    for (char c : s) {
        if (t->sons.find(c) == t->sons.end())
            t->sons.insert({c, new Node});
        t = t->sons[c];
    }
    t->count += 1;
}

int Delete(Node *t, const string &s, int pos = 0)
{
    if (pos >= s.size()) {
        if (t->count > 0)
            t->count -= 1;
    } else {
        if (t->sons.find(s[pos]) != t->sons.end()) {
            if (Delete(t->sons[s[pos]], s, pos + 1))
                t->sons.erase(s[pos]);
        }
    }

    if (t->count <= 0 && t->sons.size() <= 0) {
        delete t;
        return 1;
    }
    return 0;
}

int FindCount(Node *t, const string &s)
{
    for (char c : s) {
        if (t->sons.find(c) == t->sons.end())
            return 0;
        t = t->sons[c];
    }
    return t->count;
}

int LongestPrefix(Node *t, const string &s)
{
    int len = 0;
    for (char c : s) {
        if (t->sons.find(c) == t->sons.end())
            return len;
        t = t->sons[c];
        ++len;
    }
    return len;
}

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

    Node *trie = new Node;

    int op;
    string word;
    while (fin >> op >> word) {
        if (op == 0)
            Insert(trie, word);
        else if (op == 1)
            Delete(trie, word);
        else if (op == 2)
            fout << FindCount(trie, word) << "\n";
        else if (op == 3)
            fout << LongestPrefix(trie, word) << "\n";
    }

    return 0;
}