Pagini recente » Cod sursa (job #1345488) | Cod sursa (job #81293) | Cod sursa (job #1550206) | Cod sursa (job #2154288) | Cod sursa (job #2137816)
#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 TrieNode {
/* number of words that pass through this node */
int wordCount;
TrieNode* child[LMAX];
TrieNode(int val) {
wordCount = val;
for (int i = 0; i < LMAX; ++i) {
child[i] = nullptr;
}
}
};
TrieNode* root = new TrieNode(0);
void insertWord(TrieNode *node, char* word) {
if (word[0] != NULL) {
if (nextNode == nullptr) {
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 = nullptr;
} else {
nextNode->wordCount--;
}
}
}
int wordCnt(TrieNode* node, char* word) {
if (nextNode == nullptr) {
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) {
return 0;
}
if (nextNode == nullptr) {
return 0;
}
return 1 + findPrefix(nextNode, word + 1);
}
int main() {
int type;
char word[21];
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;
}