Cod sursa(job #3184218)

Utilizator Turcanu_DavidTurcanu David Turcanu_David Data 14 decembrie 2023 23:05:17
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <bits/stdc++.h>

using namespace std;

const int alpha=26;

struct node
{
    struct node *children[alpha];
    int word;
};

struct node *create(void)
{
    struct node *n=new node;

    n->word=0;

    for(int i=0; i<alpha; i++)
        n->children[i]=NULL;
    return n;
}

void insert(struct node *root, string &s)
{
    struct node *n=root;
    for(int c:s)
    {
        c-='a';
        if(!n->children[c])
            n->children[c]=create();
        n=n->children[c];
    }
    n->word++;
}

int find(struct node *root, string &s)
{
    struct node *n=root;
    for(int c:s)
    {
        c-='a';
        if(!n->children[c])
            return 0;
        n=n->children[c];
    }
    return n->word;
}

bool isEmpty(struct node *n)
{
    for(int i=0; i<alpha; i++)
    {
        if(n->children[i])
            return false;
    }
    return true;
}

node* remove(struct node *n, string &s, int p)
{
    if(!n)
        return NULL;
    if(p == s.size())
    {
        n->word--;
        if(isEmpty(n) && n->word == 0)
        {
            delete(n);
            n=NULL;
        }
        return n;
    }

    int c=s[p]-'a';
    n->children[c]=remove(n->children[c], s, p+1);

    if(isEmpty(n) && n->word == 0)
    {
        delete(n);
        n=NULL;
    }
    return n;
}

int lpref(struct node *n, string &s)
{
    int cnt=0;
    for(int c:s)
    {
        c-='a';
        if(!n->children[c])
            break;
        n=n->children[c];
        cnt++;
    }
    return cnt;
}

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

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

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