Cod sursa(job #2162119)

Utilizator rares96cheseliRares Cheseli rares96cheseli Data 12 martie 2018 01:51:40
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <bits/stdc++.h>
 
#define LMAX 26
#define nextNode node->child[word[0] - 'a']
 
using namespace std;
 
ifstream fin("trie.in");
ofstream fout("trie.out");
 
struct  __attribute__((__packed__)) TrieNode {
    /* number of words that pass through this node */
    int wordCount;
    TrieNode* child[LMAX];
 
    TrieNode(int val) {
        wordCount = val;
        memset(child, NULL, sizeof(child));
    }
};
 
void insertWord(TrieNode *node, char* word) {
    if (word[0] != NULL) {
 
        if (nextNode == NULL) {
            nextNode = new TrieNode(1);
        } else {
            nextNode->wordCount++;
        }
 
        insertWord(nextNode, word + 1);
    }
}
 
bool eraseWord(TrieNode* node, char* word) {
    if (word[0] != NULL) {
        eraseWord(nextNode, word + 1);
 
        if (nextNode->wordCount == 1) {
            delete nextNode;
            nextNode = NULL;
        } else {
            nextNode->wordCount--;
        }
    }
}
 
int wordCnt(TrieNode* node, char* word) {
    if (nextNode == NULL) {
        return 0;
    }
 
    if (word[1] == NULL) {
        int sum = 0;
 
        /* count the words that pass through the current node and are larger that "word" */
        for (int i = 0; i < LMAX; ++i) {
            if (nextNode->child[i]) {
                sum += nextNode->child[i]->wordCount;
            }
        }
        return nextNode->wordCount - sum;
    }
    return wordCnt(nextNode, word + 1);
}
 
int findPrefix(TrieNode* node, const char* word) {
    if (word[0] == NULL || nextNode == NULL) {
        return 0;
    }
 
    return 1 + findPrefix(nextNode, word + 1);
}
 
int main() {
    int type;
    char word[21];
    TrieNode* root = new TrieNode(0);
 
    while (fin >> type >> word) {
        if (type == 0) {
            insertWord(root, word);
        } else if (type == 1) {
            eraseWord(root, word);
        } else if (type == 2) {
            fout << wordCnt(root, word) << '\n';
        } else if (type == 3) {
            fout << findPrefix(root, word) << '\n';
        }
    }
    return 0;
}