Pagini recente » Cod sursa (job #1098611) | Cod sursa (job #2370363) | Cod sursa (job #2477675) | Cod sursa (job #2576062) | Cod sursa (job #3233271)
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <vector>
using namespace std;
struct TrieNode {
unordered_map<char, TrieNode*> children;
int count;
TrieNode() : count(0) {}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(const string& word) {
TrieNode* node = root;
for (char ch : word) {
if (node->children.find(ch) == node->children.end()) {
node->children[ch] = new TrieNode();
}
node = node->children[ch];
}
node->count++;
}
void remove(const string& word) {
removeHelper(root, word, 0);
}
int countOccurrences(const string& word) {
TrieNode* node = root;
for (char ch : word) {
if (node->children.find(ch) == node->children.end()) {
return 0;
}
node = node->children[ch];
}
return node->count;
}
int longestPrefix(const string& word) {
TrieNode* node = root;
int maxLength = 0, currentLength = 0;
for (char ch : word) {
if (node->children.find(ch) != node->children.end()) {
currentLength++;
node = node->children[ch];
if (node->count > 0) {
maxLength = currentLength;
}
} else {
break;
}
}
return maxLength;
}
private:
TrieNode* root;
bool removeHelper(TrieNode* node, const string& word, int depth) {
if (!node) return false;
if (depth == word.size()) {
if (node->count > 0) {
node->count--;
return node->children.empty();
}
return false;
}
char ch = word[depth];
if (removeHelper(node->children[ch], word, depth + 1)) {
delete node->children[ch];
node->children.erase(ch);
return node->children.empty() && node->count == 0;
}
return false;
}
};
int main() {
ifstream infile("trie.in");
ofstream outfile("trie.out");
Trie trie;
string command, word;
while (infile >> command >> word) {
if (command == "0") {
trie.insert(word);
} else if (command == "1") {
trie.remove(word);
} else if (command == "2") {
outfile << trie.countOccurrences(word) << endl;
} else if (command == "3") {
outfile << trie.longestPrefix(word) << endl;
}
}
infile.close();
outfile.close();
return 0;
}