Pagini recente » Cod sursa (job #700481) | Cod sursa (job #1450125) | Cod sursa (job #1705571) | Cod sursa (job #3170651) | Cod sursa (job #1482265)
#include <fstream>
#include <string>
using namespace std;
class Node {
public:
Node* children[26];
int value = 0;
Node() {
for (int i = 0; i <= 26; i++) {
children[i] = 0;
}
}
};
class Trie {
private:
Node* locate(string word) {
Node* current = &root;
for (int i = 0; i < word.length(); i++) {
if (!current->children[word.at(i) - 97]) {
current->children[word.at(i) - 97] = new Node();
}
current = current->children[word.at(i) - 97];
}
return current;
}
bool isPrefix(Node* node) {
if (!node)
return false;
for (int i = 0; i <= 26; i++) {
if (node->children[i] && node->children[i]->value > 0) {
return true;
}
if (this->isPrefix(node->children[i]))
return true;
}
return false;
}
public:
Node root;
void add(string word) {
Node* current = locate(word);
current->value++;
}
void remove(string word) {
Node* current = locate(word);
if (current->value > 0) {
current->value--;
}
}
int count(string word) {
Node* current = locate(word);
return current->value;
}
int longest_prefix(string word) {
for ( int i = word.size(); i >= 0; i--) {
string prefix = word.substr(0, i);
Node * node = this->locate(prefix);
if (this->isPrefix(node)) {
return i;
}
}
return 0;
}
};
int main()
{
ifstream fin("trie.in");
ofstream fout("trie.out");
Trie words;
string word;
int op = -3;
while (fin>>op>>word) {
if (op == 0) {
words.add(word);
} else if (op == 1) {
words.remove(word);
} else if (op == 2) {
fout<<words.count(word)<<endl;
} else if ( op == 3) {
fout<<words.longest_prefix(word)<<endl;
}
}
return 0;
}