Cod sursa(job #2707688)

Utilizator Ionut_neuer58Raducu Ioan Stefan Ionut_neuer58 Data 17 februarie 2021 16:34:26
Problema Trie Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
///#include <iostream>
#include <fstream>
#include <cstring>
const int alpha = 26;

using namespace std;

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

struct tnode
{
    int val, nrCh;
    tnode *ch[alpha];
    tnode()
    {
        val=nrCh=0;
        for(int i=0; i<alpha; i++) ch[i]=NULL;
    }
};

struct trie
{

private:
    tnode *root=new tnode;
    int depth;

    void push(tnode *&node, char *s)
    {
        if(*s=='\0') {node->val++; return;}
        if(node->ch[*s-'a']==NULL)
            node->ch[*s-'a']=new tnode,
            node->nrCh++;
        push(node->ch[*s-'a'], s+1);
    }

    bool del(tnode *&node, char *s)
    {
        if(*s=='\0')
        {
            node->val--;
            if(!node->val) return 1;
            return 0;
        }
        else if(del(node->ch[*s-'a'], s+1))
            node->nrCh--, delete node->ch[*s-'a'], node->ch[*s-'a']=NULL;
        return (!(node->nrCh) && !(node->val) && node!=root);
    }

    int nrOf(tnode *&node, char *s)
    {
        if(node==NULL) return 0;
        if(*s=='\0') return node->val;
        return nrOf(node->ch[*s-'a'], s+1);
    }

    int maxPref(tnode *&node, char *s)
    {
        if(node==NULL) return depth-1;
        if(*s=='\0') return depth;
        ++depth;
        return maxPref(node->ch[*s-'a'], s+1);
    }

public:
    void push(char *s) {push(root, s);}
    void del(char *s) {del(root, s);}
    int nrOf(char *s) {return nrOf(root, s);}
    int maxPref(char *s) {depth=0; return maxPref(root, s);}
};

int main()
{
    trie a;
    int x;
    char s[21];
    while(cin>>x>>s)
    {
        switch(x)
        {
        case 0:
            a.push(s); break;
        case 1:
            a.del(s); break;
        case 2:
            cout<<a.nrOf(s)<<'\n'; break;
        default:
            cout<<a.maxPref(s)<<'\n';
        }
    }
    return 0;
}