Cod sursa(job #2929396)

Utilizator Mircea08Tomita Mircea Stefan Mircea08 Data 25 octombrie 2022 19:49:26
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <bits/stdc++.h>
typedef struct TrieStruct {
    int endHere, contained;
    struct TrieStruct *next[26];
}Trie;
inline void addTrie(Trie *crtNode, char *word) {
    ++ (crtNode -> contained);
    if (*word == 0) {
        ++ (crtNode -> endHere);
        return;
    }
    short nextIndex = *word - 'a';
    if ((crtNode -> next[nextIndex]) == NULL)
        (crtNode -> next[nextIndex]) = (Trie*)calloc(1, sizeof(Trie));
    addTrie((crtNode -> next[nextIndex]), word + 1);
}
inline void removeTrie(Trie *crtNode, char *word) {
    -- (crtNode -> contained);
    if (*word == NULL) {
        -- (crtNode -> endHere);
        return;
    }
    short nextIndex = *word - 'a';
    removeTrie((crtNode -> next[nextIndex]), word + 1);
    if (((crtNode -> next[nextIndex]) -> contained) == 0) {
        free((crtNode -> next[nextIndex]));
        (crtNode -> next[nextIndex]) = NULL;
    }
}
inline int appearedTrie(Trie *crtNode, char *word) {
    if (*word == 0) {
        return (crtNode -> endHere);
    }
    short nextIndex = *word - 'a';
    if ((crtNode -> next[nextIndex]) == NULL)
        return 0;
    return appearedTrie((crtNode -> next[nextIndex]), word + 1);
}
inline int longestCommonPrefix(Trie *crtNode, char *word) {
    if (*word == 0)
        return 0;
    short nextIndex = *word - 'a';
    if ((crtNode -> next[nextIndex]) == NULL)
        return 0;
    return 1 + longestCommonPrefix((crtNode -> next[nextIndex]), word + 1);
}
char word[21];
int main() {
    std :: ios_base :: sync_with_stdio(0);
    std :: ifstream fin("trie.in");
    std :: ofstream fout("trie.out");
    fin >> std :: skipws;
    char task;
    Trie *trie = (Trie*)calloc(1, sizeof(Trie));
    while (fin >> task) {
        fin >> word;
        switch (task) {
            case '0': {
                addTrie(trie, word);
                break;
            }
            case '1': {
                removeTrie(trie, word);
                break;
            }
            case '2': {
                fout << appearedTrie(trie, word) << '\n';
                break;
            }
            case '3': {
                fout << longestCommonPrefix(trie, word) << '\n';
                break;
            }
        }
    }
    fin.close();
    fout.close();
    return 0;
}