Pagini recente » Cod sursa (job #2430287) | Cod sursa (job #637497) | Cod sursa (job #1956517) | Cod sursa (job #345392) | Cod sursa (job #2297980)
#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define enter cout << '\n'
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;
typedef vector <pii> vii;
typedef vector <ll> vl;
typedef vector <pll> vll;
typedef queue <int> qi;
typedef queue <pii> qii;
typedef queue <ll> ql;
typedef queue <pll> qll;
const ll INF = LLONG_MAX - 1;
const int MOD = 104659;
const int EPSILON = 0.0000000001;
const int NMAX = 2000 + 5;
const int DIMALPHA = 26;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Trie
{
Trie *fii[DIMALPHA];
int sfarsitcuvant, nrfii;
Trie()
{
memset(fii, 0, sizeof(fii));
nrfii = sfarsitcuvant = 0;
}
};
Trie *root = new Trie;
int cod;
string cuvant;
int prefix_cuvant(Trie *nod, int pos)
{
char ch = cuvant[pos] - 'a';
if (pos == (int)cuvant.size() || nod->fii[ch] == NULL)
return pos;
return prefix_cuvant(nod->fii[ch], pos + 1);
}
int aparitii_cuvant(Trie *nod, int pos)
{
char ch = cuvant[pos] - 'a';
if (pos == (int)cuvant.size())
return nod->sfarsitcuvant;
if (nod->fii[ch] != NULL)
return aparitii_cuvant(nod->fii[ch], pos + 1);
return 0;
}
int stergere_cuvant(Trie *nod, int pos)
{
char ch = cuvant[pos] - 'a';
if (pos == (int)cuvant.size())
--nod->sfarsitcuvant;
else if (stergere_cuvant(nod->fii[ch], pos + 1))
{
--nod->nrfii;
nod->fii[ch] = NULL;
}
if (nod->sfarsitcuvant == 0 && nod->nrfii == 0 && nod != root)
{
delete nod;
return 1;
}
return 0;
}
void inserare_cuvant(Trie *nod, int pos)
{
char ch = cuvant[pos] - 'a';
if (pos == (int)cuvant.size())
{
++nod->sfarsitcuvant;
return;
}
if (nod->fii[ch] == NULL)
{
nod->fii[ch] = new Trie;
++nod->nrfii;
}
inserare_cuvant(nod->fii[ch], pos + 1);
}
int main()
{
char ch;
while (!fin.eof())
{
fin >> cod >> cuvant;
if(fin.eof()) break;
if (cod == 0) inserare_cuvant(root, 0);
else if (cod == 1) stergere_cuvant(root, 0);
else if (cod == 2) fout << aparitii_cuvant(root, 0) << '\n';
else if (cod == 3) fout << prefix_cuvant(root, 0) << '\n';
fin.get(ch);
}
return 0;
}