Pagini recente » Cod sursa (job #140571) | Cod sursa (job #161822) | Cod sursa (job #3151050) | Cod sursa (job #3033142) | Cod sursa (job #2592334)
#include<fstream>
#include<iostream>
#include<string>
#define SIGMA 26
using namespace std;
class TrieNode {
private:
TrieNode* next[SIGMA];
int cnt;
public:
TrieNode() {
this->cnt = 0;
for(int i = 0; i < SIGMA; ++i)
this->next[i] = NULL;
}
void insertWord(string&, unsigned);
bool deleteWord(string&, unsigned);
unsigned searchWord(string&, unsigned);
unsigned prefixSearch(string&, unsigned);
};
void TrieNode::insertWord(string& word, unsigned pos) {
if(pos == word.size())
this->cnt++;
else {
if(this->next[word[pos] - 'a'] == NULL)
this->next[word[pos] - 'a'] = new TrieNode;
this->next[word[pos] - 'a']->insertWord(word, pos + 1);
}
}
bool TrieNode::deleteWord(string& word, unsigned pos) {
if(pos == word.size()) {
if(this->cnt == 0)
return false;
else {
this->cnt--;
return true;
}
} else {
if(this->next[word[pos] - 'a'] == NULL)
return false;
else {
bool ans = this->next[word[pos] - 'a']->deleteWord(word, pos + 1);
if(ans) {
TrieNode* son = this->next[word[pos] - 'a'];
bool toDelete = son->cnt == 0;
for(int i = 0; i < SIGMA; ++i)
toDelete &= son->next[i] == NULL;
if(toDelete) {
delete son;
this->next[word[pos] - 'a'] = NULL;
}
}
}
}
}
unsigned TrieNode::searchWord(string& word, unsigned pos) {
if(pos == word.size())
return this->cnt;
else {
if(this->next[word[pos] - 'a'] == NULL)
return 0;
else return this->next[word[pos] - 'a']->searchWord(word, pos + 1);
}
}
unsigned TrieNode::prefixSearch(string& word, unsigned pos) {
if(pos == word.size() || this->next[word[pos] - 'a'] == NULL)
return pos;
else return this->next[word[pos] - 'a']->prefixSearch(word, pos + 1);
}
TrieNode* root;
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
string s;
int op;
root = new TrieNode;
fin >> op >> s;
while(!fin.eof()) {
if(op == 0)
root->insertWord(s, 0);
else if(op == 1) {
root->deleteWord(s, 0);
} else if(op == 2)
fout << root->searchWord(s, 0) << '\n';
else fout << root->prefixSearch(s, 0) << '\n';
fin >> op >> s;
}
fin.close();
fout.close();
return 0;
}