Cod sursa(job #2870392)

Utilizator popoviciAna16Popovici Ana popoviciAna16 Data 12 martie 2022 12:12:44
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <iostream>
using namespace std;

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

struct trie
{
    int nrc = 0, nrf = 0;
    struct trie *f[26] = {};
};

trie *t = new trie;

void pune (trie *nod, char *c)
{
    if (c[0] == '\0')
    {
        nod -> nrc++;
        return;
    }
    if (nod -> f[c[0]-'a'] == NULL)
    {
        nod -> f[c[0]-'a'] = new trie;
        nod -> nrf++;
    }
    pune (nod -> f[c[0]-'a'], c+1);
}

bool sterge (trie *nod, char *c)
{
    if (c[0] == '\0')
        nod -> nrc--;
    else
    {
        if (sterge (nod -> f[c[0]-'a'], c+1) == 1)
        {
            nod -> f[c[0]-'a'] = NULL;
            nod -> nrf--;
        }
    }

    if (nod -> nrf == 0 && nod -> nrc == 0 && nod != t)
    {
        delete nod;
        return 1;
    }
    return 0;
}

int nrap (trie *nod, char *c)
{
    if (c[0] == '\0')
        return nod -> nrc;
    if (nod -> f[c[0]-'a'] != NULL)
        return nrap (nod -> f[c[0]-'a'], c+1);
    return 0;
}

int pref (trie *nod, char *c)
{
    if (c[0] == '\0')
        return 0;
    if (nod -> f[c[0]-'a'] != NULL)
        return 1 + pref (nod -> f[c[0]-'a'], c+1);
    return 0;
}

int main()
{
    int x;
    char c[21];

    while (fin >> x >> c)
    {
        if (x == 0)
            pune (t, c);
        else if (x == 1)
            sterge (t, c);
        else if (x == 2)
            fout << nrap (t, c) << '\n';
        else
            fout << pref (t, c) << '\n';
    }
    return 0;
}