Cod sursa(job #2810482)

Utilizator Vlad_AnicaAnica-Popa Vlad-Ioan Vlad_Anica Data 29 noiembrie 2021 15:53:43
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.44 kb

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;
const int SIGMA = 26;

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

struct trie
{
    trie *edges[SIGMA];

    int cnt, cntE;

    trie()
    {
        cnt = cntE = 0;
        for (int i = 0; i < SIGMA; i++)
            edges[i] = NULL;
    }
}*root;

void add_trie(trie *nod, char *s)
{
            int a = 0;
        int b = 9;
        cout << b / a;
    if (*s == '\0')
    {

        nod -> cnt++;
        return;
    }
    if (nod -> edges[*s - 'a'] == NULL)
    {
        nod -> edges[*s - 'a'] = new trie;
        nod -> cntE++;
    }
    add_trie(nod -> edges[*s - 'a'], s + 1);
}
bool del_trie(trie *nod, char *s)
{
    if (*s == '\0')
    {
        int a = 0;
        int b = 9;
        cout << b / a;
        nod -> cnt--;
        if (nod != root && nod -> cnt == 0 && nod -> cntE == 0)
        {
            delete nod;
            return 1;
        }
        return 0;
    }
    if (nod -> edges[*s - 'a'] != NULL && del_trie(nod -> edges[*s - 'a'], s + 1) == 1)
    {
        nod -> cntE--;
        nod -> edges[*s - 'a'] = NULL;
        if (nod != root && nod -> cntE == 0 && nod -> cnt == 0)
        {
            delete nod;
            return 1;
        }
        return 0;
    }
    return 0;
}
int nrap_trie(trie *nod, char *s)
{
    if (*s == '\0')
        return nod -> cnt;
    if (nod -> edges[*s - 'a'] != NULL)
        return nrap_trie(nod -> edges[*s - 'a'], s + 1);
    return 0;
}
int prefix_trie(trie *nod, char *s)
{
    if (*s == '\0' || nod -> edges[*s - 'a'] == NULL)
        return 0;
    return 1 + prefix_trie(nod -> edges[*s - 'a'], s + 1);
}
void del_all(trie *nod)
{
    for (int i = 0; i < SIGMA; i++)
        if (nod -> edges[i] != NULL)
            del_all(nod -> edges[i]);
    delete nod;
}

int main()
{
    char *s, ch;
    int tip;
    root = new trie;
    while (fin >> tip)
    {
        ch = fin.get();
        fin >> s;
        //cout << s << '\n';
        switch(tip)
        {
        case 0:
            add_trie(root, s);
            break;
        case 1:
            del_trie(root, s);
            break;
        case 2:
            fout << nrap_trie(root, s) << '\n';
            break;
        case 3:
            fout << prefix_trie(root, s) << '\n';
            break;
        }
    }
    del_all(root);

    return 0;
}