Cod sursa(job #2140570)

Utilizator Juve45UAIC Alexandru Ionita Juve45 Data 23 februarie 2018 17:22:45
Problema Trie Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
 
#define chr s[0]-'a'
 
using namespace std;
 
struct Trie{
int nrsons, words;
Trie *sons[26];
Trie (){
nrsons=0;
words=0;
for (int i=0;i<26;i++)
    sons[i]=NULL;
}
};
 
Trie *T= new Trie;
 
void ins(Trie *nod, char *s)
{
    if (!s[0])
    {
        nod->words++;
        return;
    }
    if (nod->sons[chr]==NULL)
    {
        nod->sons[chr]=new Trie;
        nod->nrsons++;
    }
    ins(nod->sons[chr], s+1);
}
 
bool del(Trie *nod, char*s)
{
    if (!s[0])
        nod->words--;
    else
    {
        if (del(nod->sons[chr],  s+1))
        {
            nod->sons[chr]=0;
            nod->nrsons--;
        }
    }
    if (nod->words==0&&nod->nrsons==0&&nod!=T)
    {
        delete nod;
        nod=nullptr;
        return 1;
    }
    return 0;
}
 
int cnt(Trie *nod, char *s)
{
    if (!s[0])
        return nod->words;
    else
    {
        if (!nod->sons[chr])
            return 0;
        return cnt(nod->sons[chr], s+1);
    }
}
 
int lcpref(Trie *nod, char*s, int niv)
{
    if (!s[0])
        return niv;
    else
    {
        if (!nod->sons[chr])
            return niv;
        return lcpref(nod->sons[chr], s+1, niv+1);
    }
}
 
ifstream fin("trie.in");
ofstream fout ("trie.out");

int main()
{
    ios_base::sync_with_stdio(0); 
    fin.tie(0);
    int op;
    char cuv[21];
    while (fin>>op>>cuv)
    {
        switch (op)
        {
            case 0: ins(T, cuv);
            break;
            case 1: del(T, cuv);
            break;
            case 2: fout<<cnt(T, cuv)<<'\n';
            break;
            case 3: fout<<lcpref(T, cuv, 0)<<'\n';
            break;
        }
    }
    return 0;
}