Cod sursa(job #1621394)

Utilizator andytosaAndrei Tosa andytosa Data 29 februarie 2016 18:50:19
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <string>

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

struct nod{
    int nr, k;
    nod *v[26];

    nod(){
        nr = 0;
        k = 0;
        for(int i = 0; i < 26; ++i)
            v[i] = 0;
    }
};
nod *trie;
string s;
int t, val, lung, n;

void update(int poz, nod *p){
    int x = s[poz] - 'a';
    if(p -> v[x] == 0)
        p -> v[x] = new nod;
    p -> v[x] -> nr += val;

    if(poz == lung - 1){
        p -> v[x] -> k += val;
        return;
    }

    update(poz + 1, p -> v[x]);
}
void gaseste(int poz, nod *p){
    int x = s[poz] - 'a';

    if(poz == lung - 1){
        n = p -> v[x] -> k;
        return;
    }

    if(p -> v[x] != 0)
        gaseste(poz + 1, p -> v[x]);
}
void prefix(int poz, nod *p){
    int x = s[poz] - 'a';

    if(poz == lung - 1)
        return;
    if(p -> v[x] == 0 || p -> v[x] -> nr == 0)
        return;

    n++;
    prefix(poz + 1, p -> v[x]);
}
int main()
{
    trie = new nod;
    while(fin >> t >> s){
        lung = s.size();
        if(t == 0){
            val = 1;
            update(0, trie);
        }
        else if(t == 1){
            val = -1;
            update(0, trie);
        }
        else if(t == 2){
            n = 0;
            gaseste(0, trie);
            fout << n << '\n';
        }
        else if(t == 3){
            n = 0;
            prefix(0, trie);
            fout << n << '\n';
        }
    }
    return 0;
}