Pagini recente » Cod sursa (job #3152483) | Cod sursa (job #2083180) | Cod sursa (job #678856) | Cod sursa (job #2967169) | Cod sursa (job #3304000)
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
typedef long long ll;
typedef long double ld;
const int alpha = 26;
struct node
{
int cnt, sz;
node *a[alpha];
node ()
{
cnt = sz = 0;
for (int i = 0; i < alpha; i++)
a[i] = NULL;
}
} *root;
void inserare(string s)
{
node *x = root;
for (char c : s)
{
if (x->a[c - 'a'] == NULL)
{
x->a[c - 'a'] = new node;
x->sz++;
}
x = x->a[c - 'a'];
}
x->cnt++;
}
void stergere(node *x, string &s, int poz)
{
if (poz == s.length())
x->cnt--;
else
{
if (x->a[s[poz] - 'a'] != NULL)
{
stergere(x->a[s[poz] - 'a'], s, poz + 1);
if (x->a[s[poz] - 'a']->sz == 0 &&
x->a[s[poz] - 'a']->cnt == 0)
{
delete x->a[s[poz] - 'a'];
x->a[s[poz] - 'a'] = NULL;
x->sz--;
}
}
}
}
int nrap(string s)
{
node *x = root;
for (char c : s)
{
if (x->a[c - 'a'] == NULL)
return 0;
x = x->a[c - 'a'];
}
return x->cnt;
}
int lcp(string s)
{
node *x = root;
int ans = 0;
for (char c : s)
{
if (x->a[c - 'a'] == NULL)
return ans;
ans++;
x = x->a[c - 'a'];
}
return ans;
}
int main()
{
root = new node;
int tip;
string s;
while(fin >> tip)
{
fin >> s;
if (tip == 0)
inserare(s);
if (tip == 1)
stergere(root, s, 0);
if (tip == 2)
fout << nrap(s) << '\n';
if (tip == 3)
fout << lcp(s) << '\n';
}
fin.close();
fout.close();
return 0;
}