Pagini recente » Cod sursa (job #54872) | Cod sursa (job #1733494) | Cod sursa (job #2958019) | Cod sursa (job #1769143) | Cod sursa (job #2949248)
#ifdef EZ
#include "./ez/ez.h"
#else
#include <bits/stdc++.h>
#endif
#define mp make_pair
#define mt make_tuple
#define ll long long
#define pb push_back
#define fi first
#define se second
using namespace std;
const string FILE_NAME = "trie";
ifstream fin (FILE_NAME + ".in");
ofstream fout (FILE_NAME + ".out");
class Nod {
private:
Nod* fii[26];
Nod* tat = nullptr;
int words_count = 0;
int childs_count = 0;
Nod* getLastCharNod(char s[])
{
Nod *nod = this;
for (int i = 0; s[i]; ++i)
{
char car = s[i]-'a';
if (nod->fii[car])
nod = nod->fii[car];
else
{
nod->fii[car] = new Nod();
nod->fii[car]->tat = nod;
nod->childs_count ++;
nod = nod->fii[car];
}
}
return nod;
}
public:
Nod()
{
fill(fii, fii + 26, nullptr);
}
void addCuv(char s[])
{
getLastCharNod(s)->words_count ++;
}
void delCuv(char s[])
{
Nod* last = getLastCharNod(s);
last->words_count --;
int i = strlen(s) - 1;
while (last && last->words_count == 0 && last->childs_count == 0)
{
Nod *aux = last;
last = last->tat;
delete aux;
last->childs_count --;
last->fii[s[i]-'a'] = nullptr;
i--;
}
}
int nrApCuv(char s[])
{
Nod* nod = this;
for (int i = 0; s[i]; ++i)
{
char car = s[i]-'a';
if (nod->fii[car])
nod = nod->fii[car];
else
return 0;
}
return nod->words_count;
}
int lcpCuv(char s[])
{
int max = 0;
Nod *nod = this; int i;
for (i = 0; s[i]; ++i)
{
char car = s[i];
if (nod->fii[car-'a'])
nod = nod->fii[car-'a'];
else
return max;
max = std::max(max, i+1);
}
return max;
}
};
int main()
{
Nod *root = new Nod;
int op; char s[21];
while (fin >> op >> s)
{
switch (op)
{
case 0:
root->addCuv(s);
break;
case 1:
root->delCuv(s);
break;
case 2:
fout << root->nrApCuv(s) << '\n';
break;
case 3:
fout << root->lcpCuv(s) << '\n';
break;
}
}
}