Pagini recente » Cod sursa (job #2066675) | Cod sursa (job #2972641) | Cod sursa (job #296419) | Cod sursa (job #1115751) | Cod sursa (job #2702552)
#include <bits/stdc++.h>
#define BUFF_SIZE 32
#define infile "trie.in"
#define outfile "trie.out"
using namespace std;
struct TrieNode
{
int cnt, c_sons;
TrieNode *next_nodes[26];
TrieNode() {
cnt = 0;
c_sons = 0;
memset(next_nodes, 0, sizeof(next_nodes));
}
};
TrieNode *root = new TrieNode;
void insert_word(TrieNode *root, const char *s)
{
if (strlen(s) == 0)
{
root->cnt++;
return;
}
int idx = (int) (*s - 'a');
if (!root->next_nodes[idx])
{
root->next_nodes[idx] = new TrieNode;
root->c_sons++;
}
insert_word(root->next_nodes[idx], ++s);
}
int delete_word(TrieNode *root, const char *s)
{
int idx = (int) (*s - 'a');
if (strlen(s) == 0)
{
root->cnt--;
}
else if (delete_word(root->next_nodes[idx], ++s))
{
root->next_nodes[idx] = 0;
root->c_sons--;
}
// Message for those who check out this solution, I know it took me some time to grasp this concept :))
// root != ::root checks whether the root inside the function is equal to the root of the entire structure
if (root->cnt == 0 && root->c_sons == 0 && root != ::root)
{
delete root;
return 1;
}
return 0;
}
int query(TrieNode *root, const char *s)
{
if (strlen(s) == 0)
return root->cnt;
int idx = (int) (*s - 'a');
if (root->next_nodes[idx] != 0)
{
return query(root->next_nodes[idx], ++s);
}
}
int largest_prefix(TrieNode *root, const char *s, unsigned int k)
{
int idx = (int) (*s - 'a');
if (strlen(s) == 0 || root->next_nodes[idx] == 0)
{
return k;
}
return largest_prefix(root->next_nodes[idx], ++s, ++k);
}
int main()
{
freopen(infile, "r", stdin);
freopen(outfile, "w", stdout);
char* word;
word = (char*) malloc(BUFF_SIZE);
fgets(word, 32, stdin);
while (!feof(stdin))
{
const char op = word[0];
if (op == '0')
{
insert_word(root, word + 2);
}
else if (op == '1')
{
delete_word(root, word + 2);
}
else if (op == '2')
{
printf("%d\n", query(root, word + 2));
}
else if (op == '3')
{
printf("%d\n", largest_prefix(root, word + 2, 0));
}
fgets(word, 32, stdin);
}
fclose(stdin);
fclose(stdout);
return 0;
}