Pagini recente » Cod sursa (job #1126102) | Cod sursa (job #2478291) | Cod sursa (job #2398440) | Cod sursa (job #1833572) | Cod sursa (job #2651225)
// Trie - infoarena
#include <fstream>
#include <cstring>
using namespace std;
class Dictionary {
public:
Dictionary() : root {new Trie()}
{}
void insert(const char* word)
{
insert(word, root);
}
void remove(const char* word)
{
remove(word, root);
}
int query(const char* word)
{
return query(word, root);
}
int prefix(const char* word)
{
return prefix(word, root);
}
private:
struct Trie {
Trie(const char& ch = 'a') : ch {ch}, cnt {0}, sonsCnt {0}
{}
char ch;
int cnt;
int sonsCnt;
Trie* sons[26];
};
void insert(const char* word, Trie* trie)
{
if (strlen(word) == 0)
{
trie->cnt++;
return;
}
if (trie->sons[word[0] - 'a'] == nullptr)
{
trie->sons[word[0] - 'a'] = new Trie(word[0]);
trie->sonsCnt++;
}
insert(word + 1, trie->sons[word[0] - 'a']);
}
bool remove(const char* word, Trie* trie) // true if trie has been deleted
{
if (strlen(word) == 0)
trie->cnt--;
else
{
if (remove(word + 1, trie->sons[word[0] - 'a']))
{
trie->sons[word[0] - 'a'] = nullptr;
trie->sonsCnt--;
}
}
if (trie->cnt == 0 && trie->sonsCnt == 0 && trie != root)
{
delete trie;
return true;
}
return false;
}
int query(const char* word, Trie* trie)
{
if (trie == nullptr)
return 0;
if (strlen(word) == 0)
return trie->cnt;
return query(word + 1, trie->sons[word[0] - 'a']);
}
int prefix(const char* word, Trie* trie)
{
if (trie == nullptr || strlen(word) == 0)
return -1;
return 1 + prefix(word + 1, trie->sons[word[0] - 'a']);
}
Trie* root;
};
ifstream fin("trie.in");
ofstream fout("trie.out");
Dictionary dict;
int main()
{
int type;
char word[21];
while (fin >> type >> word)
switch (type)
{
case 0:
dict.insert(word);
break;
case 1:
dict.remove(word);
break;
case 2:
fout << dict.query(word) << '\n';
break;
case 3:
fout << dict.prefix(word) << '\n';
break;
}
fin.close();
fout.close();
}