Pagini recente » Cod sursa (job #1557688) | Cod sursa (job #2922949) | Cod sursa (job #1901933) | Cod sursa (job #2237209) | Cod sursa (job #2964469)
#include<fstream>
using namespace std;
const int ALPHABET_SIZE = 26;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
int apparitions = 0;
struct TrieNode *parent;
};
struct TrieNode *getNode(void)
{
struct TrieNode *pNode = new TrieNode;
pNode->apparitions = 0;
for (int i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
return pNode;
}
void insert(struct TrieNode *root, string key)
{
for (unsigned int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
if (!root->children[index]){
root->children[index] = getNode();
root->children[index]->parent = root;
}
root = root->children[index];
}
root->apparitions++;
}
int getNumberOfApparitions(struct TrieNode *root, string key)
{
for (unsigned int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
if (!root->children[index])
return 0;
root = root->children[index];
}
return root->apparitions;
}
bool checkIfNodeHasChildren(struct TrieNode *root){
for (unsigned int i = 0; i < ALPHABET_SIZE; i++)
if(root->children[i] != NULL){
return true;
}
return false;
}
void deleteNode(struct TrieNode *root, string key)
{
for (unsigned int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
root = root->children[index];
}
root->apparitions--;
int keyLength = key.length()-1;
while(!checkIfNodeHasChildren(root) && root->apparitions == 0){
root = root->parent;
root->children[key[keyLength] - 'a'] = NULL;
keyLength--;
}
}
unsigned int getLongestPrefix(struct TrieNode *root, string key)
{
unsigned int i = 0;
for(i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
if (!root->children[index])
return i;
root = root->children[index];
}
return i;
}
int main()
{
int operation;
string word, substring;
struct TrieNode *root = getNode();
while(fin>>operation>>word){
if(operation == 0){
insert(root, word);
}
if(operation == 1){
deleteNode(root, word);
}
if(operation == 2){
fout<<getNumberOfApparitions(root, word)<<endl;
}
if(operation == 3){
fout<<getLongestPrefix(root, word)<<endl;
}
}
return 0;
}