Pagini recente » Cod sursa (job #2495479) | Rating Fieraru Ciprian (Fieraru_Ciprian) | Cod sursa (job #1877348) | Cod sursa (job #1643325) | Cod sursa (job #2300959)
#include <bits/stdc++.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
const int Nmax = 26;
struct TrieNode {
TrieNode* children[Nmax];
int appearances, nrChildren;
TrieNode () {
memset(children, 0, sizeof(children));
nrChildren = appearances = 0;
}
};
TrieNode *root = new TrieNode;
void insert (string word) {
TrieNode *current = root;
for (auto ch: word) {
TrieNode *nextNode = current->children[ch - 'a'];
if (nextNode == NULL) {
nextNode = new TrieNode;
current->nrChildren++;
current->children[ch - 'a'] = nextNode;
}
current = nextNode;
}
current->appearances++;
}
bool deleteWord (TrieNode *current, string word, int idx) {
if (idx == (int)word.size()) {
current->appearances--;
} else {
TrieNode *nextNode = current->children[word[idx] - 'a'];
if (deleteWord(nextNode, word, idx + 1) == true) {
current->children[word[idx] - 'a'] = NULL;
current->nrChildren--;
}
}
if (current->appearances == 0 && current->nrChildren == 0 && current != root) {
delete current;
return true;
}
return false;
}
void deleteWord (string word) {
deleteWord(root, word, 0);
}
int getAppearances (string word) {
TrieNode *current = root;
for (auto ch: word) {
TrieNode *nextNode = current->children[ch - 'a'];
if (nextNode == NULL) {
return 0;
}
current = nextNode;
}
return current->appearances;
}
int getLongestPrefix (string word) {
TrieNode *current = root;
int ans = 0;
for (auto ch: word) {
TrieNode *nextNode = current->children[ch - 'a'];
if (nextNode == NULL) {
return ans;
}
++ans;
current = nextNode;
}
return ans;
}
int main() {
ios::sync_with_stdio(false); in.tie(0); out.tie(0);
int op;
string word;
while (in >> op >> word) {
if (op == 0) {
insert(word);
}
if (op == 1) {
deleteWord(word);
}
if (op == 2) {
out << getAppearances(word) << "\n";
}
if (op == 3) {
out << getLongestPrefix(word) << "\n";
}
}
in.close(); out.close();
return 0;
}