Cod sursa(job #2959351)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 30 decembrie 2022 19:04:01
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>
#include <string>

using namespace std;

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

const int sigma = 26;

int sz;
string s;

struct str{
    int ct, fii;
    str *fiu[sigma];
    str()
    {
        ct = 0;
        fii = 0;
        for (int i = 0; i < 26; i++)
        {
            fiu[i] = 0;
        }
    }
};

str *t = new str;

void ins (str *nod, int poz)
{
    if (poz == sz)
    {
        nod -> ct++;
        return;
    }
    if (nod -> fiu[(s[poz] - 'a')] == 0)
    {
        nod -> fiu[(s[poz] - 'a')] = new str;
        nod -> fii++;
    }
    ins(nod -> fiu[(s[poz] - 'a')], poz + 1);
}

bool del (str *nod, int poz)
{
    if (poz == sz)
    {
        nod -> ct--;
    }
    else
    {
        if (del(nod -> fiu[(s[poz] - 'a')], poz + 1))
        {
            nod -> fiu[(s[poz] - 'a')] = 0;
            nod -> fii--;
        }
    }
    if (nod -> ct == 0 && nod -> fii == 0 && nod != t)
    {
        delete nod;
        return 1;
    }
    return 0;
}

int querry (str *nod, int poz)
{
    if (poz == sz)
    {
        return nod -> ct;
    }
    if (nod -> fiu[(s[poz] - 'a')] > 0)
    {
        return querry(nod -> fiu[(s[poz] - 'a')], poz + 1);
    }
    return 0;
}

int pref (str *nod, int poz)
{
    if (poz == sz || nod -> fiu[(s[poz] - 'a')] == 0)
    {
        return poz;
    }
    return pref(nod -> fiu[(s[poz] - 'a')], poz + 1);
}

int main ()
{
    int op;
    while (in >> op >> s)
    {
        sz = s.size();
        if (op == 0)
        {
            ins(t, 0);
        }
        if (op == 1)
        {
            del(t, 0);
        }
        if (op == 2)
        {
            out << querry(t, 0) << '\n';
        }
        if (op == 3)
        {
            out << pref(t, 0) << '\n';
        }
    }
    in.close();
    out.close();
    return 0;
}