Cod sursa(job #3184311)

Utilizator Turcanu_DavidTurcanu David Turcanu_David Data 15 decembrie 2023 11:24:34
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>
#define int long long

using namespace std;

const int alpha=26;

char s[25];

struct node
{
    node *children[alpha];
    int word=0, nrchild=0;
};

void setup(node *n)
{
    for(int i=0; i<alpha; i++)
    {
        n->children[i]=NULL;
    }
}

void insert(struct node *n, char *p)
{
    n->nrchild++;
    if(*p == NULL)
        n->word++;
    else
    {
        if(n->children[p[0]-'a'] == NULL)
        {
            n->children[p[0]-'a'] = new node;
            setup(n->children[p[0]-'a']);
        }
        insert(n->children[p[0]-'a'], p+1);
    }
}

void del(node *n, char *p)
{
    n->nrchild--;
    if(*p == NULL)
        n->word--;
    else
        del(n->children[p[0]-'a'], p+1);
}

int find(struct node *n, char *p)
{
    if(*p == NULL)
        return n->word;
    if(n->children[p[0]-'a'] == NULL)
        return 0;
    return find(n->children[p[0]-'a'], p+1);
}


int lpref(struct node *n, char *p)
{
    if(n->nrchild == 0)
        return -1;
    if(*p == NULL || n->children[p[0]-'a'] == NULL)
        return 0;
    return lpref(n->children[p[0]-'a'], p+1)+1;
}

int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

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

    char c;
    struct node *root = new node;
    setup(root);
    while(cin>>c>>s)
    {
        if(c == '0')
            insert(root, s);
        if(c == '1')
            del(root, s);
        if(c == '2')
            cout<<find(root, s)<<'\n';
        if(c == '3')
            cout<<lpref(root, s)<<'\n';
    }
    return 0;
}