Cod sursa(job #2906744)

Utilizator VladPislaruPislaru Vlad Rares VladPislaru Data 27 mai 2022 10:46:25
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <bits/stdc++.h>

using namespace std;

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

struct Nod
{
    int fr; /// de cate ori apare un cuvant
    int fr_pre; /// de cate ori apare prefixul
    Nod *leg[26];
    Nod ()
    {
        fr = 0;
        fr_pre = 0;
        for (int i = 0; i < 26; i++)
            leg[i] = NULL;
    }
};


class Trie
{
protected:
    Nod *root;
public:
    Trie()
    {
        root = new Nod;
    }
    void Add (string w)
    {
        Nod *aux = root;
        aux -> fr_pre++;
        for (int i = 0; w[i]; i++)
        {
            if (aux -> leg[w[i] - 'a'] == NULL)
            {
                Nod *q;
                q = new Nod;
                aux -> leg[w[i] - 'a'] = q;
            }
            aux =  aux -> leg[w[i] - 'a'];
            aux -> fr_pre++;
        }
        aux -> fr++;
    }
    void Erase (string w)
    {
        Nod * aux = root;
        aux -> fr_pre--;
        for (int i = 0; w[i]; i++)
        {
            aux = aux -> leg[w[i] - 'a'];
            aux -> fr_pre--;
        }
        aux -> fr--;
    }
    int NrAparitii (string w)
    {
        Nod *aux = root;
        for (int i = 0; w[i]; i++)
        {
            if (aux -> leg[w[i] - 'a'] == NULL || aux -> fr_pre == 0)
                return 0;
            aux = aux -> leg[w[i] - 'a'];
        }
        return aux -> fr;
    }
    int LongestPref (string w)
    {
        Nod *aux = root;
        int ans = 0;
        for ( ;w[ans]; ans++)
        {

            if (aux -> fr_pre == 0)
                return ans - 1;
            if (aux -> leg[w[ans] - 'a'] == NULL)
                return ans;
            aux = aux -> leg[w[ans] - 'a'];
        }
        return ans;
    }
};

Trie T;

int main()
{
    int task;
    string s;
    while (fin >> task >> s)
    {
        if (task == 0)
            T.Add(s);
        else if (task == 1)
            T.Erase(s);
        else if (task == 2)
            fout << T.NrAparitii(s) << "\n";
        else fout << T.LongestPref(s) << "\n";
    }
    return 0;
}