Cod sursa(job #1753557)

Utilizator AplayLazar Laurentiu Aplay Data 6 septembrie 2016 17:56:29
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 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 - 1) {
        --root->letters[word[position] -'a']->passes;
        --root->letters[word[position] -'a']->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 ? 0 : root->apparitions;
}

int prefixCount(TRIE* root, char* word) {
    int result = 0;

    for (int it = 0; root != NULL && word[it] != NULL; ++it) {
        if (root->passes > 0) {
            result = it;
        }
        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);
        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;
}