Pagini recente » Cod sursa (job #3267316) | Cod sursa (job #1087674) | Cod sursa (job #443792) | Cod sursa (job #820721) | Cod sursa (job #2300911)
#include <bits/stdc++.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
const int Nmax = 26;
struct TrieNode {
TrieNode* children[Nmax];
int appearances, nrChildren;
bool endOfWord;
TrieNode () {
memset(children, 0, sizeof(children));
nrChildren = appearances = 0;
endOfWord = false;
}
};
class Trie {
private:
TrieNode *root;
bool deleteWord (TrieNode *current, string word, int idx) {
if (idx == (int)word.size()) {
current->appearances--;
} else {
TrieNode *nextNode = current->children[word[idx] - 'a'];
if (deleteWord(nextNode, word, idx + 1) == true) {
current->children[word[idx] - 'a'] = NULL;
current->nrChildren--;
}
}
if (current->appearances == 0 && current->nrChildren == 0 && current != this->root) {
delete current;
return true;
}
return false;
}
public:
Trie () {
root = new TrieNode;
}
void insert (string word) {
TrieNode *current = this->root;
for (auto ch: word) {
TrieNode *nextNode = current->children[ch - 'a'];
if (nextNode == NULL) {
nextNode = new TrieNode;
current->nrChildren++;
current->children[ch - 'a'] = nextNode;
}
current = nextNode;
}
current->appearances++;
current->endOfWord = true;
}
void deleteWord (string word) {
deleteWord(this->root, word, 0);
}
int getAppearances (string word) {
TrieNode *current = this->root;
for (auto ch: word) {
TrieNode *nextNode = current->children[ch - 'a'];
if (nextNode == NULL) {
return 0;
}
current = nextNode;
}
return current->appearances;
}
int getLongestPrefix (string word) {
TrieNode *current = this->root;
int ans = 0;
for (auto ch: word) {
TrieNode *nextNode = current->children[ch - 'a'];
if (nextNode == NULL) {
return ans;
}
++ans;
current = nextNode;
}
return ans;
}
~Trie () {
delete root;
}
};
int main() {
ios::sync_with_stdio(false); in.tie(0); out.tie(0);
Trie *myTrie = new Trie;
int op;
string word;
while (in >> op >> word) {
if (op == 0) {
myTrie->insert(word);
}
if (op == 1) {
myTrie->deleteWord(word);
}
if (op == 2) {
out << myTrie->getAppearances(word) << "\n";
}
if (op == 3) {
out << myTrie->getLongestPrefix(word) << "\n";
}
}
in.close(); out.close();
return 0;
}