Cod sursa(job #2297397)

Utilizator FrequeAlex Iordachescu Freque Data 5 decembrie 2018 19:50:01
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.4 kb
#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;
    int nrfii;

    Trie()
    {
        memset(fii, 0, sizeof(fii));
        nrfii = 0;
        sfarsitcuvant = 0;
    }
};

int cod;
string cuvant;

int prefix_cuvant(Trie *nod, int pos)
{
    if (pos < cuvant.size() && nod->fii[cuvant[pos] - 'a'])
        return prefix_cuvant(nod->fii[cuvant[pos] - 'a'], pos + 1);
    return pos;
}

int aparitii_cuvant(Trie *nod, int pos)
{
    if (pos < cuvant.size())
        return aparitii_cuvant(nod->fii[cuvant[pos] - 'a'], pos + 1);
    return nod->fii[cuvant[pos] - 'a']->sfarsitcuvant;
}

void stergere_cuvant(Trie *nod, int pos)
{
    if (pos < cuvant.size() - 1)
        stergere_cuvant(nod->fii[cuvant[pos] - 'a'], pos + 1);

    if (pos == cuvant.size() - 1)
        --nod->fii[cuvant[pos] - 'a']->sfarsitcuvant;
    if (nod->fii[cuvant[pos] - 'a']->sfarsitcuvant == 0 && nod->fii[cuvant[pos] - 'a']->nrfii == 0)
        nod->fii[cuvant[pos] - 'a'] = NULL;
}

void inserare_cuvant(Trie *nod, int pos)
{
    if (nod->fii[cuvant[pos] - 'a'] != NULL)
        inserare_cuvant(nod->fii[cuvant[pos] - 'a'], pos + 1);
    else
    {
        nod->fii[cuvant[pos] - 'a'] = new Trie;
        ++nod->nrfii;
    }

    if (pos == (int)cuvant.size() - 1) ++nod->fii[cuvant[pos] - 'a']->sfarsitcuvant;
}

int main()
{
    Trie *root = new Trie;

    while (!fin.eof())
    {
        fin >> cod >> cuvant;
        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';
    }

    return 0;
}