Pagini recente » Cod sursa (job #2697521) | Cod sursa (job #3138823) | Cod sursa (job #1960490) | Cod sursa (job #1634759) | Cod sursa (job #2381101)
#include <bits/stdc++.h>
#include <unordered_map>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
class TrieNode
{
TrieNode* children[26];
int cnt = 0, childrenCount = 0;
public:
TrieNode()
{
for (int i = 0; i < 26; ++i)
children[i] = nullptr;
}
void insert(string const& s, int index = 0)
{
if (index == s.size())
{
++cnt;
return;
}
if (children[s[index] - 'a'] == nullptr)
children[s[index] - 'a'] = new TrieNode(),
++childrenCount;
children[s[index] - 'a']->insert(s, index + 1);
}
bool remove(string const& s, int index = 0)
{
if (index == s.size())
{
--cnt;
return cnt <= 0 && childrenCount <= 0;
}
if (children[s[index] - 'a'] != nullptr)
{
bool removeNext = children[s[index] - 'a']->remove(s, index + 1);
if (removeNext)
delete children[s[index] - 'a'],
children[s[index] - 'a'] = nullptr,
--childrenCount;
return cnt <= 0 && childrenCount <= 0;
}
}
int count(string const& s, int index = 0)
{
if (index == s.size())
return cnt;
if (children[s[index] - 'a'] != nullptr)
return children[s[index] - 'a']->count(s, index + 1);
else
return 0;
}
int prefix(string const& s, int index = 0)
{
if (index == s.size())
return s.size();
if (children[s[index] - 'a'] != nullptr)
return children[s[index] - 'a']->prefix(s, index + 1);
else
return index;
}
};
int main()
{
int op;
string s;
TrieNode trie;
while (!f.eof() && f >> op >> s)
switch (op)
{
case 0:
trie.insert(s);
break;
case 1:
trie.remove(s);
break;
case 2:
g << trie.count(s) << '\n';
break;
case 3:
g << trie.prefix(s) << '\n';
break;
}
return 0;
}