Cod sursa(job #2137392)

Utilizator ARobertAntohi Robert ARobert Data 20 februarie 2018 19:28:49
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <bits/stdc++.h>

#define chr s[0]-'a'

using namespace std;

struct Trie{
int nrsons, words,nrpass;
Trie *sons[26];
Trie (){
nrsons=0;
words=0;
nrpass=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++;
    }
    if (nod->sons[chr]->nrpass==1)
    {
        nod->nrsons++;
        nod->sons[chr]->nrpass=0;
    }
    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)
    {
        nod->nrpass=1;
    }
    return 0;
}

int cnt(Trie *nod, char *s)
{
    if (!s[0])
        return nod->words;
    else
    {
        if (nod->sons[chr]->nrpass==1)
            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]||nod->sons[chr]->nrpass==1)
            return niv;
        return lcpref(nod->sons[chr], s+1, niv+1);
    }
}

int main()
{
    ifstream cin("trie.in");
    ofstream cout ("trie.out");
    ios_base::sync_with_stdio(0); cin.tie(0);
    int op;
    char cuv[21];
    while (cin>>op>>cuv)
    {
        switch (op)
        {
            case 0: ins(T, cuv);
            break;
            case 1: del(T, cuv);
            break;
            case 2: cout<<cnt(T, cuv)<<'\n';
            break;
            case 3: cout<<lcpref(T, cuv, 0)<<'\n';
            break;
        }
    }
    return 0;
}