Pagini recente » Monitorul de evaluare | Borderou de evaluare (job #2560770) | Cod sursa (job #2900739) | Borderou de evaluare (job #1405714) | Cod sursa (job #2702381)
#include <bits/stdc++.h>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct trie
{
int ap, fin = 0;
trie *v[26], *par;
trie()
{
for (auto &i : v)
i = nullptr;
par = nullptr;
ap = 0;
fin = 0;
}
} *rad = new trie;
void insert(string);
void erase(string);
int count(string);
int prefix(string);
int main()
{
int c;
string s;
while (f >> c)
{
f >> s;
if (!c)
insert(s);
else if (c == 1)
erase(s);
else if (c == 2)
g << count(s) << '\n';
else
g << prefix(s) << '\n';
}
return 0;
}
void insert(string s)
{
auto ac = rad;
for (const char &ch : s)
{
if (ac->v[ch - 'a'] == nullptr)
{
ac->v[ch - 'a'] = new trie;
ac->v[ch - 'a']->par = ac;
}
ac = ac->v[ch - 'a'];
ac->ap++;
}
ac->fin++;
}
void erase(string s)
{
auto ac = rad;
for (const char &ch : s)
ac = ac->v[ch - 'a'];
for (int i = s.size() - 1; ac != nullptr && i >= 0; i--)
{
ac->ap--;
ac = ac->par;
if (ac->v[s[i] - 'a']->ap == 0)
{
delete (ac->v[s[i] - 'a']);
ac->v[s[i] - 'a'] = nullptr;
}
}
}
int count(string s)
{
auto ac = rad;
for (const char &ch : s)
{
if (!(ac->v[ch - 'a']))
return 0;
ac = ac->v[ch - 'a'];
}
return ac->fin;
}
int prefix(string s)
{
int r = 0;
auto ac = rad;
for (const char &ch : s)
{
if (!(ac->v[ch - 'a']))
return r;
r++;
ac = ac->v[ch - 'a'];
}
return s.size();
}