Pagini recente » Cod sursa (job #3241619) | Rating Breaban Daniel-Vasile (BreabanDaniel) | Cod sursa (job #1963249) | Cod sursa (job #3279600) | Cod sursa (job #3204749)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
using namespace std;
struct TrieNode {
map<char, TrieNode*> children;
int count;
TrieNode() {
count = 0;
}
};
class Trie {
TrieNode *root;
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode *current = root;
for (char c : word) {
if (!current->children.count(c)) {
current->children[c] = new TrieNode();
}
current = current->children[c];
}
current->count++;
}
int find(string word) {
TrieNode *current = root;
for (char c : word) {
if (!current->children.count(c)) {
return 0;
}
current = current->children[c];
}
return current->count;
}
int longestCommonPrefix(string word) {
TrieNode *current = root;
int prefix_length = 0;
for (char c : word) {
if (!current->children.count(c)) {
break;
}
current = current->children[c];
prefix_length++;
}
return prefix_length;
}
};
int main() {
ifstream in("trie.in");
ofstream out("trie.out");
Trie trie;
int n;
in >> n;
for (int i = 0; i < n; i++) {
int op;
string word;
in >> op >> word;
switch (op) {
case 0:
trie.insert(word);
break;
case 1:
trie.find(word);
break;
case 2:
out << trie.find(word) << endl;
break;
case 3:
out << trie.longestCommonPrefix(word) << endl;
break;
}
}
in.close();
out.close();
return 0;
}