Cod sursa(job #2240087)

Utilizator shantih1Alex S Hill shantih1 Data 12 septembrie 2018 13:24:41
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <cstring>
#include <cstdio>
#define CH *ch-'a'

using namespace std;

int rz;
bool ok;
char s[32],*p,op;

struct trie
{
    int cnt,nrf;
    trie *fiu[26];
    trie ()
    {
        cnt=nrf=0;
        memset(fiu, 0, sizeof(fiu));
    }
};
trie *T = new trie;

bool pot(trie *nd)
{
    return (nd->cnt==0 && nd->nrf==0 && nd!=T);
}
int op1(trie *nd,char *ch)
{
    if(*ch=='\n')
    {
        nd->cnt--;
        ok=pot(nd);
        if(ok)  delete nd;
        return ok;
    }
    int r=op1(nd->fiu[CH], ch+1);
    if(r)
    {
        nd->fiu[CH]=0;
        nd->nrf--;
        ok=pot(nd);
        if(ok)  delete nd;
        return ok;
    }
    return 0;
}
void merg (trie *nd,char *ch)
{
    if(*ch=='\n')
    {
        if(s[0]=='0')   nd->cnt++;
        if(s[0]=='2')   printf("%d\n",nd->cnt);
        return;
    }
    if(nd->fiu[CH]==0)
    {
        if(s[0]=='2')
        {
            printf("0\n");
            return;
        }
        nd->fiu[CH] = new trie;
        nd->nrf++;
    }
    else rz++;
    merg(nd->fiu[CH], ch+1);
}
int op3 (trie *nd,char *ch)
{
    if(*ch=='\n'||nd->fiu[CH]==0)    return 0;
    return 1+op3(nd->fiu[CH], ch+1);
}
int main() {

    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    while(fgets(s, 32, stdin)){

        rz=0;
        if(s[0]=='0'||s[0]=='2')   merg(T,s+2);
        if(s[0]=='3')   printf("%d\n",op3(T,s+2));
        if(s[0]=='1')   op1(T,s+2);
    }
    return 0;
}