Cod sursa(job #2985597)

Utilizator pifaDumitru Andrei Denis pifa Data 26 februarie 2023 18:09:53
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 100005, SIGMA = 26;

struct Trie
{
    int freq, wordsInSubtree;
    Trie* children[SIGMA];

    Trie()
    {
        freq = wordsInSubtree = 0;
        for(int i = 0; i < SIGMA; i++)
            children[i] = NULL;
    }
};
Trie* trie = new Trie();
void insert(Trie* root, char* s)
{
    if(s[0] == '\0')
    {
        root->freq++;
        return;
    }
    if(root->children[s[0]-'a'] == NULL)
    {
        root->children[s[0]-'a'] = new Trie();
        root->wordsInSubtree++;
    }
    insert(root->children[s[0]-'a'], s + 1);
}

bool erase(Trie* root, char* s)
{
    if(s[0] == '\0')
        root->freq--;
    else if(erase(root->children[s[0]-'a'], s + 1))
    {
        root->children[s[0]-'a'] = NULL;
        root->wordsInSubtree--;
    }
    if(root->freq == 0 && root->wordsInSubtree == 0 && root != trie)
    {
        delete root;
        return true;
    }
    return false;
}

int count(Trie* root, char* s)
{
    if(s[0] == '\0')
        return root->freq;
    if(root->children[s[0]-'a'] == NULL)
        return 0;
    return count(root->children[s[0]-'a'], s + 1);
}

int lcp(Trie* root, char* s, int l = 0)
{
    if(s[0] == '\0' || root->children[s[0]-'a'] == NULL)
        return l;
    return lcp(root->children[s[0]-'a'], s + 1, l + 1);
}
int main()
{
    char *s = new char[101];
    int op;
    while(in >> op >> s)
    {
        if(op == 0)
            insert(trie, s);
        else if(op == 1)
            erase(trie, s);
        else if(op == 2)
            out << count(trie, s) << '\n';
        else
            out << lcp(trie, s) << '\n';
    }
    return 0;
}