Pagini recente » Monitorul de evaluare | Cod sursa (job #446551) | Cod sursa (job #930260) | Cod sursa (job #2254638) | Cod sursa (job #2930200)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
const int kN = 26;
struct Trie{
int freq = 0, prefix = 0;
Trie *sons[kN];
Trie(){
memset(sons, 0, sizeof(sons));
freq = 0;
prefix = 0;
}
};
Trie *root = new Trie;
void addTrie(Trie *root, char s[]){
char ch = s[0];
if (ch == NULL){
root -> freq += 1;
}
else{
if (root -> sons[ch - 'a'] == NULL){
root -> sons[ch - 'a'] = new Trie;
}
root -> sons[ch - 'a'] -> prefix += 1;
addTrie(root -> sons[ch - 'a'], s + 1);
}
}
void deleteTrie (Trie *root, char s[]){
char ch = s[0];
if (ch == NULL){
root -> freq -= 1;
}
else{
root -> sons[ch - 'a'] -> prefix -= 1;
deleteTrie(root -> sons[ch - 'a'], s + 1);
}
}
int CountTrie (Trie *root, char s[]){
char ch = s[0];
if (ch == NULL){
return root -> freq;
}
if (root -> sons[ch - 'a'] == NULL){
return 0;
}
return CountTrie(root -> sons[ch - 'a'], s + 1);
}
int PrefixTrie (Trie *root, char s[], int cnt){
char ch = s[0];
if (ch == NULL){
return cnt;
}
if (root -> sons[ch - 'a'] == NULL || root -> sons[ch - 'a'] -> prefix == 0){
return cnt;
}
return PrefixTrie(root -> sons[ch - 'a'], s + 1, cnt + 1);
}
int main(){
int op;
char s[kN];
while (fin >> op >> s){
if (op == 0){
addTrie(root, s);
}
if (op == 1){
deleteTrie(root, s);
}
if (op == 2){
fout << CountTrie(root, s) << '\n';
}
if (op == 3){
fout << PrefixTrie(root, s, 0) << '\n';
}
}
}