Pagini recente » Cod sursa (job #514730) | Cod sursa (job #234587) | Cod sursa (job #2397050) | Cod sursa (job #234579) | Cod sursa (job #3322003)
#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
class TrieNode
{
public:
TrieNode* children[26];
bool isLeaf;
int valid;
int appearance;
TrieNode()
{
isLeaf = false;
appearance = 0;
valid = 0;
for (int i = 0; i < 26; i++)
{
children[i] = nullptr;
}
}
};
void insert(TrieNode* root, const string& key)
{
TrieNode* curr = root;
for (char c : key)
{
if (curr->children[c - 'a'] == nullptr)
{
TrieNode* newNode = new TrieNode();
curr->children[c - 'a'] = newNode;
}
curr = curr->children[c - 'a'];
curr->valid++;
//cout<<curr->valid<<" ";
}
curr->isLeaf = true;
curr->appearance++;
}
int search(TrieNode* root, const string& key)
{
TrieNode* curr = root;
for (char c : key)
{
if (curr->children[c - 'a'] == nullptr)
return 0;
curr = curr->children[c - 'a'];
}
return curr->appearance;
}
int Prefix(TrieNode* root, const string& prefix)
{
TrieNode* curr = root;
int count=0;
for (char c : prefix)
{
if (curr->children[c - 'a'] == nullptr || curr->children[c-'a']->valid==0)
break;
curr = curr->children[c - 'a'];
count++;
}
return count;
}
void RemoveAppearance(TrieNode* root, const string& key)
{
TrieNode* curr = root;
for (char c : key)
{
curr = curr->children[c - 'a'];
curr->valid--;
//cout << curr->valid << " ";
}
curr->appearance--;
}
int main()
{
TrieNode* root = new TrieNode();
pair <int, string> p;
while (fin >>p.first >> p.second)
{
if (p.first == 0)
insert(root, p.second);
else if (p.first == 1)
RemoveAppearance(root, p.second);
else if (p.first == 2)
fout << search(root, p.second) << endl;
else if (p.first == 3)
fout << Prefix(root, p.second) << endl;
}
fin.close();
fout.close();
return 0;
}