Pagini recente » Cod sursa (job #978814) | Cod sursa (job #3273648) | Cod sursa (job #2124268) | Cod sursa (job #125906) | Cod sursa (job #1831831)
#include <bits/stdc++.h>
using namespace std;
#define ALFA 26
class Trie;
class Node {
private:
int visited, word_end;
Node* son[ALFA];
public:
Node() {
this->visited = 0;
this->word_end = 0;
for (auto& node : this->son)
node = nullptr;
}
~Node() {
for (auto node : this->son)
delete node;
}
friend Trie;
};
class Trie {
private:
Node* root = nullptr;
int nr_words;
const int offset = 'a';
public:
Trie() {
this->nr_words = 0;
this->root = new Node;
}
int countAparitions(string word) {
Node* current = this->root;
string :: iterator left = word.begin();
string :: iterator right = word.end();
for (left; left != right; left++) {
int x = *left - offset;
if (!current->son[x])
return 0;
current = current->son[x];
}
return current->word_end;
}
void insertWord(string word) {
Node* current = this->root;
string :: iterator left = word.begin();
string :: iterator right = word.end();
current->visited++;
for (left; left != right; left++) {
int x = *left - offset;
if (!current->son[x])
current->son[x] = new Node();
current = current->son[x];
current->visited++;
}
current->word_end++;
}
void deleteWord(string word) {
Node* current = this->root;
string :: iterator left = word.begin();
string :: iterator right = word.end();
current->visited--;
for (left; left != right; left++) {
int x = *left - offset;
if (!current->son[x])
return;
current = current->son[x];
current->visited--;
}
current->word_end--;
if (current->word_end < 0)
current->word_end = 0;
}
int getLongestPrefix(string word) {
Node* current = this->root;
string :: iterator left = word.begin();
string :: iterator right = word.end();
int lg = 0;
for (left; left != right; left++) {
int x = *left - offset;
if (!current->son[x])
return lg;
current = current->son[x];
if (!current->visited)
return lg;
lg++;
}
return lg;
}
int countWords() {
return this->nr_words;
}
};
ifstream fin("trie.in");
ofstream fout("trie.out");
int main() {
Trie* myTrie = new Trie();
int task;
string S;
while (fin >> task >> S) {
switch (task) {
case 0:
myTrie.insertWord(S);
break;
case 1:
myTrie.deleteWord(S);
break;
case 2:
fout << myTrie.countAparitions(S) << "\n";
break;
case 3:
fout << myTrie.getLongestPrefix(S) << "\n";
break;
}
}
return 0;
}