Pagini recente » Cod sursa (job #621564) | Cod sursa (job #1456172) | Cod sursa (job #781400) | Cod sursa (job #729186) | Cod sursa (job #2952903)
#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");
struct Trie {
Trie* fii[26];
int cuv;
Trie()
{
fill(fii, fii + 26, nullptr);
cuv = 0;
}
} *root = new Trie;
int countNonNull(Trie* v[26])
{
int cnt = 0;
for (int i = 0; i < 26; ++i)
if (v[i])
cnt++;
return cnt;
}
void addWord(Trie *nod, int pos, string &s)
{
if (pos == s.size())
return (void) (nod->cuv ++);
char lit = s[pos] - 'a';
if (nod->fii[lit] == nullptr)
nod->fii[lit] = new Trie;
addWord(nod->fii[lit], pos+1, s);
}
bool delWord(Trie *nod, int pos, string &s)
{
if (pos == s.size())
{
nod->cuv --;
if (nod->cuv == 0 && countNonNull(nod->fii) == 0)
{
delete nod;
return true;
}
return false;
}
char lit = s[pos] - 'a';
if (delWord(nod->fii[lit], pos+1, s))
nod->fii[lit] = nullptr;
if (nod->cuv == 0 && countNonNull(nod->fii) == 0)
{
delete nod;
return true;
}
return false;
}
int nrApWord(Trie *nod, int pos, string &s)
{
if (pos == s.size())
return nod->cuv;
char lit = s[pos] - 'a';
if (nod->fii[lit])
return nrApWord(nod->fii[lit], pos+1, s);
return 0;
}
int lcpWord(Trie *nod, int pos, string &s)
{
if (pos == s.size())
return pos;
char lit = s[pos] - 'a';
if (nod->fii[lit])
return lcpWord(nod->fii[lit], pos+1, s);
return pos;
}
int main()
{
int op; string s;
while (fin >> op >> s)
{
if (op == 0)
addWord(root, 0, s);
if (op == 1)
delWord(root, 0, s);
if (op == 2)
fout << nrApWord(root, 0, s) << '\n';
if (op == 3)
fout << lcpWord(root, 0, s) << '\n';
}
}