Cod sursa(job #2370043)

Utilizator AplayLazar Laurentiu Aplay Data 6 martie 2019 10:26:19
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.35 kb
#include <bits/stdc++.h>
 
#define MAXLENGTH 21
#define LETTERS 26
 
using namespace std;
 
typedef struct trie {
    int passes;
    int apparitions;
    struct trie* letters[LETTERS];
} TRIE;
 
TRIE* newNode() {
    TRIE* node = new TRIE;
 
    node->apparitions = node->passes = 0;
    for (int it = 0; it < LETTERS; ++it)
        node->letters[it] = NULL;
 
    return node;
}
 
void trieAdd(TRIE* root, char* word) {
    int index;
 
    for (int it = 0; word[it] != NULL; ++it) {
        index = word[it] - 'a';
        if (root->letters[index] == NULL) {
            root->letters[index] = newNode();
        }
        root = root->letters[index];
        ++root->passes;
    }
 
    ++root->apparitions;
}
 
void trieDelete(TRIE* root, char* word, int position, int limit) {
    if (position == limit) {
        --root->passes;
        --root->apparitions;
        return;
    }
 
    int index = word[position] - 'a';
    trieDelete(root->letters[index], word, position + 1, limit);
    if (root->letters[index]->passes == 0) {
        delete root->letters[index];
        root->letters[index] = NULL;
    }
    --root->passes;
}
 
int trieCount(TRIE* root, char* word) {
    int it;
 
    for (it = 0; root != NULL && word[it] != NULL; ++it) {
        root = root->letters[word[it] - 'a'];
    }
 
    return word[it] != NULL || root == NULL ? 0 : root->apparitions;
}
 
int prefixCount(TRIE* root, char* word) {
    int result = 0;
 
    for (int it = 0; root != NULL && word[it] != NULL; ++it) {
        if (root->letters[word[it] - 'a'] != NULL)
            ++result;
        else break;
        root = root->letters[word[it] - 'a'];
    }
 
    return result;
}
 
int main() {
    char word[MAXLENGTH];
    int operation;
    TRIE* root = newNode();
 
    root->apparitions = -1;
 
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
 
    while (!feof(stdin)) {
        scanf("%d %s\n", &operation, word);
            if (!strcmp(word, "colbarie")) {
        int a = 3;
    }
        switch(operation) {
        case 0:
            trieAdd(root, word);
            break;
        case 1:
            trieDelete(root, word, 0, strlen(word));
            break;
        case 2:
            printf("%d\n", trieCount(root, word));
            break;
        case 3:
            printf("%d\n", prefixCount(root, word));
            break;
        }
    }
 
    return 0;
}