Pagini recente » Cod sursa (job #1035783) | Cod sursa (job #956262) | Cod sursa (job #72218) | Cod sursa (job #2082953) | Cod sursa (job #3146554)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int SIGMA = 26;
const int DIM = 20;
int type;
char text[DIM + 1];
struct Trie {
int freq;
int words;
Trie* children[SIGMA];
Trie() {
freq = 0;
words = 0;
for(int i = 0; i < SIGMA; i++) {
children[i] = nullptr;
}
}
};
Trie root;
void insert(Trie* root, char* text) {
if(*text == '\0') {
root->freq++;
root->words++;
} else {
if(root->children[text[0] - 'a'] == nullptr) {
root->children[text[0] - 'a'] = new Trie();
}
root->children[text[0] - 'a']->freq++;
insert(root->children[text[0] - 'a'], text + 1);
}
}
void erase(Trie* root, char* text) {
if(*text == '\0') {
root->freq--;
root->words--;
} else {
if(root->children[text[0] - 'a'] != nullptr) {
root->children[text[0] - 'a']->freq--;
erase(root->children[text[0] - 'a'], text + 1);
}
}
}
int count(Trie* root, char* text) {
if(*text == '\0') {
return root->words;
} else {
if(root->children[text[0] - 'a'] == nullptr) {
return 0;
}
if(root->children[text[0] - 'a']->freq == 0) {
return 0;
}
return count(root->children[text[0] - 'a'], text + 1);
}
}
int prefix(Trie* root, char* text, int cnt = 0) {
if(*text == '\0') {
return cnt;
} else {
if(root->children[text[0] - 'a'] == nullptr) {
return cnt;
}
if(root->children[text[0] - 'a']->freq == 0) {
return cnt;
}
return prefix(root->children[text[0] - 'a'], text + 1, cnt + 1);
}
}
int main() {
while(fin >> type >> text) {
if(type == 0) {
insert(&root, text);
} else if(type == 1) {
erase(&root, text);
} else if(type == 2) {
fout << count(&root, text) << '\n';
} else if(type == 3) {
fout << prefix(&root, text) << '\n';
}
}
return 0;
}