Pagini recente » Cod sursa (job #251552) | Cod sursa (job #374166) | Cod sursa (job #1132045) | Cod sursa (job #2968645)
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
#include <queue>
#include <unordered_map>
#include <sstream>
#include <set>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int ALPH_SIZE = 26;
class Trie {
class Node {
public:
char c;
bool isWord;
char noAppearances;
size_t depth;
Node* children[ALPH_SIZE];
Node(char c, size_t depth) {
this->c = c;
this->isWord = false;
this->noAppearances = 0;
this->depth = depth;
for (int i = 0; i < ALPH_SIZE; i++)
this->children[i] = NULL;
}
};
private:
Node* root;
Node* getNode(string word) {
Node* currentNode = root;
for (size_t i = 0; i < word.length(); i++) {
char c = word[i];
if (currentNode->children[c - 'a'] == NULL)
return currentNode;
if (currentNode != root && currentNode->children[c - 'a']->noAppearances == 0)
return currentNode;
currentNode = currentNode->children[c - 'a'];
}
return currentNode;
}
public:
Trie() {
root = new Node('\0', 0);
}
void insert(string word) {
Node* currentNode = root;
for (int i = 0; i < word.length(); i++) {
char c = word[i];
if (currentNode->children[c - 'a'] == NULL)
currentNode->children[c - 'a'] = new Node(c, currentNode->depth + 1);
currentNode = currentNode->children[c - 'a'];
currentNode->noAppearances++;
}
currentNode->isWord = true;
}
void remove(string word) {
Node* currentNode = root;
for (int i = 0; i < word.length(); i++) {
char c = word[i];
if (currentNode->children[c - 'a'] == NULL)
return;
currentNode = currentNode->children[c - 'a'];
currentNode->noAppearances--;
}
currentNode->isWord = false;
}
Node* search(string word) {
Node* node = getNode(word);
return node;
}
size_t noAppearances(string word) {
Node* node = this->search(word);
return (node->isWord == true) ? node->noAppearances : 0;
}
size_t longestPrefix(string prefix) {
Node* node = this->getNode(prefix);
return node->depth;
}
};
class Solution {
private:
void insert(string word) {
root->insert(word);
}
void remove(string word) {
root->remove(word);
}
size_t returnAppearances(string word) {
return root->noAppearances(word);
}
size_t longestPrefix(string word) {
return root->longestPrefix(word);
}
public:
Trie* root = new Trie;
void solve() {
int type;
string word;
while (fin.eof() == false) {
fin >> type >> word;
if (type == 0)
this->insert(word);
else if (type == 1)
this->remove(word);
else if (type == 2)
fout << this->returnAppearances(word) << endl;
else if (type == 3)
fout << this->longestPrefix(word) << endl;
}
}
};
int main() {
Solution solution;
solution.solve();
fin.close();
fout.close();
return 0;
}