Pagini recente » Cod sursa (job #3270482) | Cod sursa (job #3124973) | Cod sursa (job #3172658) | Diferente pentru implica-te/arhiva-educationala intre reviziile 22 si 223 | Cod sursa (job #3123470)
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
const int SIGMA = 'z' - 'a' + 1;
struct trieNode {
vector<trieNode*> children;
int pass, end;
trieNode() {
children.assign(SIGMA, nullptr);
pass = end = 0;
}
};
trieNode* root = new trieNode();
void insertTrie(trieNode* root, string& word, int idx) {
root -> pass++;
if (idx == word.size()) {
root -> end++;
return;
}
int child = word[idx] - 'a';
if (root -> children[child] == nullptr) {
root -> children[child] = new trieNode();
}
insertTrie(root -> children[child], word, idx + 1);
}
bool deleteTrie(trieNode* root, string& word, int idx) {
root -> pass--;
if (idx == word.size()) {
root -> end--;
if (root -> pass == 0) {
delete root;
return true;
}
return false;
}
int child = word[idx] - 'a';
if (deleteTrie(root -> children[child], word, idx + 1)) {
root -> children[child] = nullptr;
}
if (root -> pass == 0) {
delete root;
return true;
}
return false;
}
int countTrie(trieNode* root, string& word) {
for (char ch : word) {
root = root -> children[ch - 'a'];
if (root == nullptr) {
return 0;
}
}
return root -> end;
}
int commonPrefixTrie(trieNode* root, string& word) {
for (int idx = 0; idx < word.size(); idx++) {
root = root -> children[word[idx] - 'a'];
if (root == nullptr) {
return idx;
}
}
return word.size();
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
int opType;
string word;
while (cin >> opType >> word) {
if (opType == 0) {
insertTrie(root, word, 0);
} else if (opType == 1) {
deleteTrie(root, word, 0);
} else if (opType == 2) {
cout << countTrie(root, word) << "\n";
} else {
cout << commonPrefixTrie(root, word) << "\n";
}
}
return 0;
}