Cod sursa(job #1807609)

Utilizator preda.andreiPreda Andrei preda.andrei Data 16 noiembrie 2016 19:17:43
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <map>
#include <string>

using namespace std;

struct Nod
{
    int aparitii = 0;
    map<char, Nod*> urmator;
};

void Adauga(Nod *t, const string &s)
{
    for (char c : s) {
        if (t->urmator.find(c) == t->urmator.end())
            t->urmator.insert({c, new Nod});
        t = t->urmator[c];
    }
    ++t->aparitii;
}

void Sterge(Nod *t, const string &s, unsigned poz = 0)
{
    if (poz == s.size()) {
        --t->aparitii;
    } else {
        Nod *urm = t->urmator[s[poz]];
        Sterge(urm, s, poz + 1);

        if (urm->aparitii == 0 && urm->urmator.empty()) {
            t->urmator.erase(s[poz]);
            delete urm;
        }
    }
}

int Aparitii(Nod *t, const string &s)
{
    for (char c : s) {
        if (t->urmator.find(c) == t->urmator.end())
            return 0;
        t = t->urmator[c];
    }
    return t->aparitii;
}

int LungimePrefix(Nod *t, const string &s)
{
    unsigned len = 0;
    while (len < s.size() && t->urmator.find(s[len]) != t->urmator.end()) {
        t = t->urmator[s[len]];
        ++len;
    }
    return len;
}

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

    Nod *trie = new Nod;
    while (!fin.eof()) {
        int r;
        fin >> r;
        fin.get();

        string s;
        getline(fin, s);

        if (!fin.good()) continue;
        if (r == 0)
            Adauga(trie, s);
        else if (r == 1)
            Sterge(trie, s);
        else if (r == 2)
            fout << Aparitii(trie, s) << "\n";
        else fout << LungimePrefix(trie, s) << "\n";
    }

    return 0;
}