Pagini recente » Cod sursa (job #808596) | Cod sursa (job #1345201) | Cod sursa (job #2117599) | Cod sursa (job #1361575) | Cod sursa (job #2835778)
#include <bits/stdc++.h>
#define int long long
#define ll pair<long long, long long>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie {
int cnt, nr_sons;
trie *sons[26];
trie() {
for (int i = 0; i < 26; ++i) {
sons[i] = NULL;
}
cnt = nr_sons = 0;
}
};
trie *root = new trie;
void add_word(char *word) {
int len = strlen(word);
trie *cur_node = root;
for (int i = 0; i < len; ++i) {
if (cur_node->sons[word[i] - 'a'] == NULL) {
cur_node->sons[word[i] - 'a'] = new trie;
cur_node->nr_sons++;
}
cur_node = cur_node->sons[word[i] - 'a'];
if (i == len - 1) {
cur_node->cnt++;
}
}
}
bool delete_word(trie *node, char *word) {
if (*word == '\0') {
node->cnt--;
} else if (delete_word(node->sons[*word - 'a'], word + 1)) {
node->sons[*word - 'a'] = NULL;
node->nr_sons--;
}
if (node->nr_sons == 0 and node->cnt == 0 and node != root) {
delete node;
return true;
}
return false;
}
int find_occurences(char *word) {
int len = strlen(word);
trie *cur_node = root;
for (int i = 0; i < len; ++i) {
if (!cur_node->sons[word[i] - 'a']) {
return 0;
}
cur_node = cur_node->sons[word[i] - 'a'];
}
return cur_node->cnt;
}
int find_prefix(char *word) {
int len = strlen(word);
trie *cur_node = root;
for (int i = 0; i < len; ++i) {
if (!cur_node->sons[word[i] - 'a']) {
return i;
}
cur_node = cur_node->sons[word[i] - 'a'];
}
return len;
}
int32_t main() {
//ios_base::sync_with_stdio(false), cin.tie(NULL);
int tests = 1;
//cin >> tests;
while (tests--) {
char query[30];
while (fin >> query) {
char word[30];
fin >> word;
if (query[0] == '0') {
add_word(word);
} else if (query[0] == '1') {
delete_word(root, word);
} else if (query[0] == '2') {
fout << find_occurences(word) << '\n';
} else {
fout << find_prefix(word) << '\n';
}
}
}
return 0;
}