Cod sursa(job #2739466)

Utilizator stefantagaTaga Stefan stefantaga Data 8 aprilie 2021 12:42:21
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct trie
{
    int nr=0,active_sons=0;
    trie *v[28];
    trie()
    {
        nr=0;
        active_sons=0;
        for (int j=0;j<27;j++)
        {
            v[j]=nullptr;
        }
    }
} *tree = new trie;
void update ( trie *tree, char *t,int val)
{
    if (*t==0)
    {
        tree->nr+=val;
        return;
    }
    int loc=(*t-'a');
    if (tree->v[loc]==nullptr)
    {
        tree->active_sons++;
        tree->v[loc]=new trie;
    }
    update(tree->v[loc],t+1,val);
    if (val==-1)
    {
        trie *Son=tree->v[loc];
        if ((Son->nr)==0&&Son->active_sons==0)
        {
            delete(Son);
            tree->active_sons--;
            tree->v[loc]=nullptr;
        }
    }
}
int aparitii(trie *tree, char *s)
{
    if (*s==0)
    {
        return tree->nr;
    }
    int loc=(*s-'a');
    if (tree->v[loc]==nullptr)
    {
        return 0;
    }
    return aparitii(tree->v[loc],s+1);
}
int lcp(trie *tree,char *s,int nr)
{
    if (*s==0)
    {
        return nr;
    }
    int loc=(*s-'a');
    if (tree->v[loc]==nullptr)
    {
        return nr;
    }
    return lcp(tree->v[loc],s+1,nr+1);
}
int tip;
char s[25];
int main()
{
    tree->nr=1;
    while (f>>tip>>s)
    {
        if (tip==0)
        {
            update(tree,s,1);
        }
        else
        if (tip==1)
        {
            update(tree,s,-1);
        }
        else
        if (tip==2)
        {
            g<<aparitii(tree,s)<<'\n';
        }
        else
        {
            g<<lcp(tree,s,0)<<'\n';
        }
    }
    return 0;
}