Pagini recente » Cod sursa (job #1388860) | Cod sursa (job #1485781)
#include <fstream>
#include <algorithm>
#include <string>
#include <stack>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
class Trie {
private:
struct Node {
int words_pass, words_end;
Node *children[26];
Node() : words_pass(0), words_end(0), children{nullptr} {}
~Node() {
// for (int i = 0; i < 26; ++i)
// if (children[i] != nullptr)
// delete children[i];
}
};
Node *root;
public:
Trie() : root(new Node) {}
~Trie() {
// if (root != nullptr)
// delete root;
}
void add(const string &word) {
Node *curr = root;
for (unsigned int i = 0; i < word.size(); ++i) {
if (curr->children[word[i] - 'a'] == nullptr)
curr->children[word[i] - 'a'] = new Node;
curr = curr->children[word[i] - 'a'];
++curr->words_pass;
}
++curr->words_end;
}
void remove(const string &word) {
Node *curr = root;
for (unsigned int i = 0; i < word.size(); ++i) {
curr = curr->children[word[i] - 'a'];
--curr->words_pass;
}
--curr->words_end;
}
int apparitions(const string &word) {
Node *curr = root;
for (unsigned int i = 0; i < word.size(); ++i)
if (curr->children[word[i] - 'a'] == nullptr)
return 0;
else
curr = curr->children[word[i] - 'a'];
return curr->words_end;
}
int longest_prefix(const string &word) {
Node *curr = root;
int len = 0;
for (unsigned i = 0; i < word.size(); ++i)
if (curr->children[word[i] - 'a'] != nullptr &&
curr->children[word[i] - 'a']->words_pass != 0) {
curr = curr->children[word[i] - 'a'];
++len;
} else
break;
return len;
}
};
int main() {
int op;
string word;
Trie trie;
while (in >> op) {
in >> word;
if (op == 0)
trie.add(word);
else if (op == 1)
trie.remove(word);
else if (op == 2)
out << trie.apparitions(word) << '\n';
else
out << trie.longest_prefix(word) << '\n';
}
return 0;
}