Pagini recente » Cod sursa (job #1866614) | Cod sursa (job #847737) | Cod sursa (job #1715714) | Cod sursa (job #1374456) | Cod sursa (job #2842647)
#include <fstream>
#include <iostream>
const int SIGMA = 26;
struct Trie {
int freq;
int words;
Trie* children[SIGMA];
Trie() {
freq = 0;
words = 0;
for (int i = 0; i < SIGMA; i++) {
children[i] = nullptr;
}
}
};
void insert(Trie* root, char* S) {
if (*S == '\0') {
root->freq++;
root->words++;
} else {
if (root->children[S[0] - 'a'] == nullptr) {
root->children[S[0] - 'a'] = new Trie();
}
root->children[S[0] - 'a']->freq++;
insert(root->children[S[0] - 'a'], S + 1);
}
}
void erase(Trie* root, char* S) {
if (*S == '\0') {
if (root->freq > 0) {
root->freq--;
root->words--;
}
} else {
if (root->children[S[0] - 'a'] != nullptr) {
root->children[S[0] - 'a']->freq--;
erase(root->children[S[0] - 'a'], S + 1);
}
}
}
int count(Trie* root, char* S) {
if (*S == '\0') {
return root->words;
} else {
if (root->children[S[0] - 'a'] == nullptr || root->children[S[0] - 'a']->freq == 0) {
return 0;
}
count(root->children[S[0] - 'a'], S + 1);
}
}
int prefix(Trie* root, char* S, int cnt = 0) {
if (*S == '\0') {
return cnt;
} else {
if (root->children[S[0] - 'a'] != nullptr && root->children[S[0] - 'a']->freq != 0) {
prefix(root->children[S[0] - 'a'], S + 1, cnt + 1);
} else {
return cnt;
}
}
}
int main() {
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
Trie root;
char* S = new char[20 + 1];
int t;
while (fin >> t) {
fin >> S;
if (t == 0) {
insert(&root, S);
} else if (t == 1) {
erase(&root, S);
} else if (t == 2) {
fout << count(&root, S) << "\n";
} else {
fout << prefix(&root, S) << "\n";
}
}
return 0;
}