Pagini recente » Cod sursa (job #1665932) | Cod sursa (job #838251) | Cod sursa (job #816602) | Cod sursa (job #2526670) | Cod sursa (job #1243994)
#include <iostream>
#include <fstream>
#include <memory>
#include <map>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct TrieNode{
map<char, unique_ptr<TrieNode>> neighbours;
int used_by;
int final;
};
void AddWord(const string& word, const int& start, TrieNode* node) {
if (start == word.size()) {
node->final++;
return;
}
if (node->neighbours[word[start]] == nullptr) {
node->neighbours[word[start]].reset(new TrieNode());
}
node->neighbours[word[start]]->used_by++;
AddWord(word, start + 1, node->neighbours[word[start]].get());
}
void RemoveWord(const string& word, const int& start, TrieNode* node) {
if (start == word.size()) {
node->final--;
return;
}
if (node->neighbours[word[start]] == nullptr) {
return;
}
if (--node->neighbours[word[start]]->used_by == 0) {
node->neighbours[word[start]].reset();
return;
}
RemoveWord(word, start + 1, node->neighbours[word[start]].get());
}
int CountWord(const string& word, const int& start, TrieNode* node) {
if (start == word.size()) {
return node->final;
}
if (node->neighbours[word[start]] == nullptr) {
return 0;
}
return CountWord(word, start+1, node->neighbours[word[start]].get());
}
int LongestPrefix(const string& word, const int& start, TrieNode* node) {
if (start == word.size()) {
return 0;
}
if (node->neighbours[word[start]] != nullptr) {
return 1 + LongestPrefix(word, start + 1,
node->neighbours[word[start]].get());
}
return 0;
}
int main (int argc, char const *argv[]) {
int code;
string word;
TrieNode root;
while(in>>code>>word) {
if (code == 0) {
AddWord(word, 0, &root);
}
if (code == 1) {
RemoveWord(word, 0, &root);
}
if (code == 2) {
out<< CountWord(word, 0, &root) << "\n";
}
if (code == 3) {
out << LongestPrefix(word, 0, &root) << "\n";
}
}
return 0;
}