Cod sursa(job #2553563)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 22 februarie 2020 09:49:55
Problema Trie Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");
const int SIGMA = 26, MAX = 25;

char str[MAX];

int inline toDigit(char x)
{
    return x - 'a';
}

struct Node
{
    Node *son[SIGMA];
    int con;
    Node()
    {
        for (int i = 0; i < SIGMA; ++i)
            son[i] = nullptr;
        con = 0;
    }
}*root;

void addWord(Node *node, int ind, int n)
{
    if (ind == n) {
        ++node->con;
        return;
    }
    int temp = toDigit(str[ind]);
    if (node->son[temp] == nullptr)
        node->son[temp] = new Node();
    addWord(node->son[temp], ind + 1, n);
}

void deleteWord(Node *node, int ind, int n)
{
    if (ind == n) {
        --node->con;
        return;
    }
    int temp = toDigit(str[ind]);
    deleteWord(node->son[temp], ind + 1, n);
    if (node->son[temp]->con == 0 && ind == n - 1) {
        delete node->son[temp];
        node->son[temp] = nullptr;
    }
}

int findCount(Node *node, int ind, int n)
{
    if (ind == n)
        return node->con;
    int temp = toDigit(str[ind]);
    if (node->son[temp] == nullptr)
        return 0;
    return findCount(node->son[temp], ind + 1, n);
}

int findLength(Node *node, int ind, int n)
{
    if (ind == n)
        return n;
    int temp = toDigit(str[ind]);
    if (node->son[temp] == nullptr)
        return ind;
    return findLength(node->son[temp], ind + 1, n);
}

int main()
{
    int type;
    root = new Node();
    while(fin >> type) {
        fin >> str;
        fin.get();
        if (type == 0)
            addWord(root, 0, strlen(str));
        else if (type == 1)
            deleteWord(root, 0, strlen(str));
        else if (type == 2)
            fout << findCount(root, 0, strlen(str)) << '\n';
        else
            fout << findLength(root, 0, strlen(str)) << '\n';
    }
    return 0;
}