Cod sursa(job #1580805)

Utilizator Narcys01Ciovnicu Narcis Narcys01 Data 26 ianuarie 2016 09:50:34
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>
#include <cstring>

#define CH (*s - 'a')

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct Trie
{
    int cnt, nrfii;
    Trie *fiu[30];
    Trie()
    {
        cnt = nrfii = 0;
        memset(fiu, 0, sizeof(fiu));
    }
};

Trie *T;

void Ins(Trie *nod, char *s)
{
    if (*s == 0)
    {
        nod->cnt++;
        return;
    }
    if (nod->fiu[CH] == 0)
    {
        nod->fiu[CH] = new Trie;
        nod->nrfii++;
    }
    Ins(nod->fiu[CH], s+1);
}

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

int Que(Trie *nod, char *s)
{
    if (*s == 0)
        return nod->cnt;
    if (nod->fiu[CH])
        return Que(nod->fiu[CH], s+1);
    return 0;
}

int Pre(Trie *nod, char *s, int k)
{
    if (*s == 0 || nod->fiu[CH] == 0)
        return k;
    return Pre(nod->fiu[CH], s+1, k+1);
}

int main()
{
    int nr;
    char line[32];
    T = new Trie;
    while (fin >> nr >> line)
    {
        if (nr == 0) Ins(T, line);
        else if (nr == 1) Del(T, line);
        else if (nr == 2) fout << Que(T, line) << "\n";
        else fout << Pre(T, line, 0) << "\n";
    }
}