Pagini recente » Cod sursa (job #2959999) | Cod sursa (job #1977305) | Cod sursa (job #1605909) | Cod sursa (job #2957435) | Cod sursa (job #2229676)
#include <bits/stdc++.h>
using namespace std;
struct Trie {
int apparitions;
Trie *letters[26];
Trie () {
apparitions = 0;
for (int i = 0; i < 26; ++i) {
letters[i] = nullptr;
}
}
} *root;
void insert (string s) {
Trie *current = root;
current->apparitions += 1;
for (auto x : s) {
int currentPosition = x - 'a';
if (current->letters[currentPosition] == nullptr) {
current->letters[currentPosition] = new Trie();
}
current = current->letters[currentPosition];
current->apparitions += 1;
}
}
void erase (string s) {
Trie *current = root;
current->apparitions -= 1;
for (auto x : s) {
int currentPosition = x - 'a';
assert(current->letters[currentPosition] != nullptr);
current = current->letters[currentPosition];
current->apparitions -= 1;
}
}
int getApparitions (string s) {
Trie *current = root;
for (auto x : s) {
int currentPosition = x - 'a';
if (current->letters[currentPosition] == nullptr) {
return 0;
}
current = current->letters[currentPosition];
}
int sumOfSons = 0;
for (int i = 0; i < 26; ++i) {
if (current->letters[i] == nullptr) continue;
sumOfSons += current->letters[i]->apparitions;
}
return current->apparitions - sumOfSons;
}
int getLongestPrefix (string s) {
int length = 0;
Trie *current = root;
for (auto x : s) {
int currentPosition = x - 'a';
if (current->letters[currentPosition] == nullptr || current->letters[currentPosition]->apparitions == 0) {
return length;
}
length += 1;
current = current->letters[currentPosition];
}
return length;
}
int main()
{
ifstream fin ("trie.in");
ofstream fout ("trie.out");
root = new Trie();
int type;
while (fin >> type) {
string s;
fin >> s;
if (type == 0) insert(s);
if (type == 1) erase(s);
if (type == 2) fout << getApparitions(s) << '\n';
if (type == 3) fout << getLongestPrefix(s) << '\n';
}
return 0;
}