Pagini recente » Cod sursa (job #3278503) | Cod sursa (job #1899283) | Cod sursa (job #1355377) | Cod sursa (job #2450755) | Cod sursa (job #1976992)
#include <bits/stdc++.h>
using namespace std;
#define ALFA 26
ifstream fin("trie.in");
ofstream fout("trie.out");
class Trie;
class TrieNode {
public:
int visited;
int finish;
TrieNode* alfa[ALFA];
TrieNode() {
this->visited = 0;
this->finish = 0;
for (int i = 0; i < ALFA; ++i)
this->alfa[i] = nullptr;
}
friend Trie;
};
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
void insertWord(TrieNode*& node, const string& word, int idx) {
node->visited++;
if (idx >= word.length()) {
node->finish++;
return;
}
if (!node->alfa[word[idx] - 'a'])
node->alfa[word[idx] - 'a'] = new TrieNode();
this->insertWord(node->alfa[word[idx] - 'a'], word, idx + 1);
}
void eraseWord(TrieNode*& node, const string& word, int idx) {
node->visited--;
if (idx >= word.length()) {
node->finish--;
return;
}
this->eraseWord(node->alfa[word[idx] - 'a'], word, idx + 1);
}
int countAparition(TrieNode*& node, const string& word, int idx) {
if (idx >= word.length()) {
return node->finish;
}
if (!node->alfa[word[idx] - 'a'])
return 0;
return this->countAparition(node->alfa[word[idx] - 'a'], word, idx + 1);
}
int getLongestPref(TrieNode*& node, const string& word, int idx) {
if (idx >= word.length()) {
return -1;
}
if (!node->visited)
return -1;
if (!node->alfa[word[idx] - 'a'])
return 0;
return 1 + this->getLongestPref(node->alfa[word[idx] - 'a'], word, idx + 1);
}
};
int main() {
int t;
string word;
Trie* myTrie = new Trie();
while (fin >> t >> word) {
if (t == 0) {
myTrie->insertWord(myTrie->root, word, 0);
}
else if (t == 1) {
myTrie->eraseWord(myTrie->root, word, 0);
}
else if (t == 2) {
fout << myTrie->countAparition(myTrie->root, word, 0) << "\n";
}
else if (t == 3) {
fout << myTrie->getLongestPref(myTrie->root, word, 0) << "\n";
}
}
return 0;
}