Cod sursa(job #2267881)

Utilizator Victor_InczeVictor Incze Victor_Incze Data 24 octombrie 2018 10:10:21
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>
#define CH (*s - 'a')

using namespace std;

struct Trie
{
    int cnt, nrfii;
    Trie *fiu[26];

    Trie()
    {
        cnt=nrfii=0;
        memset(fiu,0,sizeof(fiu));
    }
};

Trie *T=new Trie;

void ins(Trie *nod, char *s)
{
    if (*s=='\n')
    {
        nod->cnt++;
        return;
    }
    if (nod->fiu[CH]==0)
    {
        nod->fiu[CH]=new Trie;
        nod->nrfii++;
    }
    ins(nod->fiu[CH],s+1);
}

int del(Trie *nod, char *s)
{
    if (*s=='\n')
        nod->cnt--;
    else
        if (del(nod->fiu[CH],s+1))
        {
            nod->fiu[CH]=0;
            nod->nrfii--;
        }
    if (nod->cnt==0 && nod->nrfii==0 && nod!=T)
    {
        delete nod;
        return 1;
    }
    return 0;
}

int que(Trie *nod, char *s)
{
    if (*s=='\n')
        return nod->cnt;
    if (nod->fiu[CH])
        return que(nod->fiu[CH],s+1);
    return 0;
}

int pre(Trie *nod, char *s, int k)
{
    if (*s=='\n' || nod->fiu[CH]==0)
        return k;
    return pre(nod->fiu[CH],s+1,k+1);
}

int main()
{
    char line[32];
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    fgets(line,32,stdin);
    while (!feof(stdin))
    {
        switch(line[0])
        {
            case '0': ins(T,line+2); break;
            case '1': del(T,line+2); break;
            case '2': printf("%d\n",que(T,line+2)); break;
            case '3': printf("%d\n",pre(T,line+2,0)); break;
        }
        fgets(line,32,stdin);
    }
    return 0;
}