Cod sursa(job #2706943)

Utilizator Ionut_neuer58Raducu Ioan Stefan Ionut_neuer58 Data 16 februarie 2021 10:11:24
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
///#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

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

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

trie *a=new trie;

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

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

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

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

void coutTrie(trie *node, char s[])
{
    if(node==NULL) return;
    if(node->val) cout<<s<<' '<<node->val<<'\n';
    char s1[20]{0};
    for(int i=0; i<26; i++)
    {
        strcpy(s1, s);
        s1[strlen(s1)]=char(i+'a');
        coutTrie(node->ch[i], s1);
    }
}

int main()
{
    char cer, s[21];
    while(cin>>cer>>s)
    {
        if(cer=='0') trieAdd(a, s);
        else if(cer=='1') trieErase(a, s);
        else if(cer=='2') cout<<nrApar(a, s)<<'\n';
        else cout<<maxPref(a, s, 0)<<'\n';
    }
    ///coutTrie(a, "");
    return 0;
}