Pagini recente » Cod sursa (job #627344) | Cod sursa (job #791431)
Cod sursa(job #791431)
#include <fstream>
#include <cstring>
#include <sstream>
#define MAX_COMM_SIZE 23
#define MAX_WORD_SIZE 20
#define ALPHABET_SIZE 'z' - 'a' + 1
#define charToIndex(x) x - 'a'
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
class TrieNode
{
private:
TrieNode* letter[ALPHABET_SIZE];
int nr_words;
int nr_kids;
public:
TrieNode()
{
nr_words = 0;
nr_kids = 0;
memset(letter, 0, sizeof(letter));
}
void insert(char* word)
{
if(letter[charToIndex(*word)] == NULL)
{
letter[charToIndex(*word)] = new TrieNode;
nr_kids++;
}
if(strlen(word) == 1)
letter[charToIndex(*word)] -> nr_words++;
else
letter[charToIndex(*word)] -> insert(word + 1);
}
void erase(char* word)
{
if(strlen(word) != 1)
letter[charToIndex(*word)] -> erase(word + 1);
else
letter[charToIndex(*word)] -> nr_words--;
if (letter[charToIndex(*word)] -> nr_words == 0
&& letter[charToIndex(*word)] -> nr_kids == 0)
{
delete letter[charToIndex(*word)];
letter[charToIndex(*word)] = NULL;
nr_kids--;
}
}
int word_count(char* word)
{
if(letter[charToIndex(*word)] == NULL)
return 0;
if(strlen(word) == 1)
return letter[charToIndex(*word)] -> nr_words;
else
return letter[charToIndex(*word)] -> word_count(word + 1);
}
int longest_common_prefix(char* word)
{
static int level = 0; //nivelul nodului curent (nivel litera - 1)
static int max = 0;
level++;
if(letter[charToIndex(*word)] == NULL || strlen(word) == 0)
{
if (nr_kids >= 1)
max = level - 1;
else
max = level - 2;
int aux = max;
max = level = 0; //reset
return aux;
}
if((strlen(word) == 1 && letter[charToIndex(*word)] -> nr_kids >= 1)
|| (letter[charToIndex(*word)] -> nr_kids >= 2))
{
max = level;
}
return letter[charToIndex(*word)] -> longest_common_prefix(word + 1);
}
};
int main()
{
TrieNode* trie_root = new TrieNode;
char command[MAX_COMM_SIZE], word[MAX_WORD_SIZE];
int comm;
stringstream buffer;
while(f.getline(command, MAX_COMM_SIZE))
{
buffer.str(command);
buffer >> comm >> word;
buffer.clear();
switch(comm)
{
case 0:
trie_root -> insert(word);
break;
case 1:
trie_root -> erase(word);
break;
case 2:
g << trie_root -> word_count(word) << '\n';
break;
case 3:
g << trie_root -> longest_common_prefix(word) << '\n';
}
}
return 0;
}