Cod sursa(job #2630268)

Utilizator pregoliStana Andrei pregoli Data 24 iunie 2020 22:43:41
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>
#define newline '\n'
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
///***********************
const int SIGMA = 26, NMAX = 30;
char s[NMAX];
int op;
struct Trie
{
    int nrW, nrSons;
    Trie *son[SIGMA];
    Trie()
    {
        nrW = nrSons = 0;
        fill(son, son + SIGMA, nullptr);
    }
};
Trie *trie = new Trie();

inline int mapping(char c)
{
    return c - 'a';
}

void insertInTrie(Trie *node, char s[])
{
    if (!*s)
    {
        node->nrW++;
        return;
    }
    if (!node->son[mapping(*s)])
    {
        node->son[mapping(*s)] = new Trie();
        node->nrSons++;
    }
    insertInTrie(node->son[mapping(*s)], s + 1);
}

bool deleteInTrie(Trie *node, char s[])
{
    if (!*s)
        node->nrW--;
    else if (deleteInTrie(node->son[mapping(*s)], s + 1))
    {
        node->son[mapping(*s)] = nullptr;
        node->nrSons--;
    }
    if (!node->nrSons && !node->nrW && node != trie)
    {
        delete node;
        return true;
    }
    return false;
}

int countW(Trie *node, char s[])
{
    if (!*s)
        return node->nrW;
    if (!node->son[mapping(*s)])
        return 0;
    return countW(node->son[mapping(*s)], s + 1);
}

int getPrefLen(Trie *node, char s[], int len)
{
    if (!*s || !node->son[mapping(*s)])
        return len;
    return getPrefLen(node->son[mapping(*s)], s + 1, len + 1);
}

int main()
{
    while (fin >> op)
    {
        fin.getline(s, NMAX);
        switch (op)
        {
        case 0:
            insertInTrie(trie, s);
            break;
        case 1:
            deleteInTrie(trie, s);
            break;
        case 2:
            fout << countW(trie, s) << newline;
            break;
        default:
            fout << getPrefLen(trie, s, 0) << newline;
        }
    }
    return 0;
}