Cod sursa(job #2086994)

Utilizator abccnuCamelia Zalum abccnu Data 12 decembrie 2017 19:24:22
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin ("trie.in");
ofstream fout ("trie.out");

struct node
{
    int ap, fr;
    node* fii[26];
    node()
    {
        fr = 0;
        ap = 0;
        for (int i = 0; i < 26; i++) fii[i] = NULL;
    }
};

node* root = new node();

int ch(char c)
{
    return (int)(c - 'a');
}

void Adauga(string str, int val)
{
    node* p = root;
    for (int i = 0; i < str.size(); i++) //adaug un fiu
    {
        int ind = ch(str[i]);
        if (p->fii[ind] == NULL) p->fii[ind] = new node();
        p = p->fii[ind];
        p->fr += val;

    }
    p->ap += val;
}


int Cauta (string x)
{
    node *p = root;

    for (int i = 0; i < x.size(); ++i)
    {
        int ind = ch(x[i]);
        if (p->fii[ind] != NULL) p = p -> fii[ind];
        else return 0;
    }

    return p->ap;

}

int cmlp(string x)
{
    node* p = root;
    int nrl = 0;

    for (int i = 0; i < x.size(); ++i)
    {
        int ind = ch(x[i]);

        if (p->fii[ind] != NULL and p->fii[ind]->fr > 0) p = p->fii[ind], nrl++;
        else break;
    }

    return nrl;


}


int main()
{
    int op;
    while (fin >> op)
    {
        string x;
        fin >> x;

        if (op == 0) /// adauga cuvantul in trie
            Adauga(x , 1);

        if (op == 1) /// sterge cuvantul
            Adauga(x, -1);

        if (op == 2)
            fout  << Cauta(x) << "\n";

        if (op == 3)
            fout << cmlp(x) << "\n";
    }
    return 0;
}