Pagini recente » Cod sursa (job #2557848) | Cod sursa (job #1845397) | Cod sursa (job #877095) | Cod sursa (job #3141944) | Cod sursa (job #1116879)
#include<fstream>
#include<cstdlib>
using namespace std;
struct TrieNode {
int prefixCount;
int endCount;
TrieNode *children[30];
TrieNode()
{
prefixCount = 0;
endCount = 0;
for(int i = 0; i < 30; i++)
{
children[i] = 0;
}
}
};
ifstream f("trie.in");
ofstream g("trie.out");
int longestPrefix(TrieNode *root, char *word, int pos, int wordLength)
{
if (pos == wordLength)
{
return wordLength;
}
if (root->children[word[pos] - 'a'] != 0)
{
return longestPrefix(root->children[word[pos] - 'a'], word, pos + 1, wordLength);
}
else
{
return pos;
}
}
int countWord(TrieNode *root, char *word, int pos, int wordLength)
{
if (pos == wordLength)
{
return root->endCount;
}
if (root->children[word[pos] - 'a'] != 0)
{
countWord(root->children[word[pos] - 'a'], word, pos + 1, wordLength);
}
else
{
return 0;
}
}
void del(TrieNode *root, char *word, int pos, int wordLength)
{
root->prefixCount--;
if (pos == wordLength)
{
root->endCount--;
return;
}
if (root -> children[word[pos] - 'a'] != 0)
{
del(root -> children[word[pos] - 'a'], word, pos + 1, wordLength);
if (root -> children[word[pos] - 'a']->prefixCount == 0 && root -> children[word[pos] - 'a']->endCount == 0)
{
delete root->children[word[pos] - 'a'];
root->children[word[pos] - 'a'] = 0;
}
}
}
void add(TrieNode *root, char *word, int pos, int wordLength)
{
root->prefixCount++;
if (pos == wordLength)
{
root->endCount++;
return;
}
if (root -> children[word[pos] - 'a'] == 0)
{
root -> children[word[pos] - 'a'] = new TrieNode();
}
add(root->children[word[pos] - 'a'], word, pos + 1, wordLength);
}
int main()
{
TrieNode root;
while (!f.eof())
{
int codop = -1;
char word[300];
f >> codop >> word;
if (codop == -1)
{
break;
}
if (codop == 0)
{
add(&root, word, 0, strlen(word));
}
if (codop == 1)
{
del(&root, word, 0, strlen(word));
}
if (codop == 2)
{
g << countWord(&root, word, 0, strlen(word)) << "\n";
}
if (codop == 3)
{
g << longestPrefix(&root, word, 0, strlen(word)) << "\n";
}
}
return 0;
}