Cod sursa(job #2661361)

Utilizator FrostfireMagirescu Tudor Frostfire Data 21 octombrie 2020 20:18:47
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

int type;
char s[30];

struct Trie
{   int cnt, nrfii;
    Trie *fiu[26];
    Trie()
        {   cnt = nrfii = 0;
            for(int i=0; i<=25; i++) fiu[i] = 0;
        }
};

Trie *T = new Trie;

void ins(Trie *nod, char *s)
{   if(!(*s))
        {   nod->cnt++;
            return;
        }
    int ch = *s - 'a';
    if(!nod->fiu[ch])
        {   nod->nrfii++;
            nod->fiu[ch] = new Trie;
        }
    ins(nod->fiu[ch], s+1);
}

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

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

int pr(Trie *nod, char *s, int k)
{   int ch = *s - 'a';
    if(!(*s) || !nod->fiu[ch]) return k;
    return pr(nod->fiu[ch], s+1, k+1);
}

int main()
{
    while(f >> type >> s)
        {   if(type == 0) ins(T, s);
            else if(type == 1) del(T, s);
            else if(type == 2) g << que(T, s) << '\n';
            else g << pr(T, s, 0) << '\n';
        }
    return 0;
}