Pagini recente » Cod sursa (job #3137790) | Cod sursa (job #477108) | Cod sursa (job #544637) | Cod sursa (job #3334003) | Cod sursa (job #3307258)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
string filename = "trie";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");
struct Node
{
Node* copii[26];
int fr;
};
void ins(Node* node, string s)
{
node->fr++;
for(auto it : s)
{
int pos = it - 'a';
if(node->copii[pos] == nullptr)
{
node->copii[pos] = new Node();
}
node = node->copii[pos];
node->fr++;
}
}
void er(Node* node, string s)
{
node->fr--;
for(auto it : s)
{
int pos = it - 'a';
node = node->copii[pos];
node->fr--;
}
}
int aparitii(Node* node, string s)
{
for(auto it : s)
{
int pos = it - 'a';
if(node->copii[pos] == nullptr)
return 0;
node = node->copii[pos];
}
int ans = node->fr;
for(int i = 0; i < 26; i++)
{
if(node->copii[i] != nullptr)
{
ans -= node->copii[i]->fr;
}
}
return ans;
}
int prefix(Node* node, string s)
{
int length = 0;
for (auto it : s)
{
int pos = it - 'a';
if (node->copii[pos] == nullptr or node->copii[pos]->fr == 0)
{
return length;
}
node = node->copii[pos];
length += 1;
}
return length;
}
int main()
{
Node *root = new Node();
int type;
string s;
while(fin >> type >> s)
{
if (type == 0)
{
ins(root, s);
}
else if (type == 1)
{
er(root, s);
}
else if (type == 2)
{
fout << aparitii(root, s) << '\n';
}
else
{
fout << prefix(root, s) << '\n';
}
}
}