Cod sursa(job #1328163)

Utilizator SpiriFlaviuBerbecariu Flaviu SpiriFlaviu Data 28 ianuarie 2015 02:37:20
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

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

struct Node
{
    int N;
    int nr;
    Node* sons[27];
    Node()
    {
        N = 0;
        memset(sons, 0, sizeof(sons));
        nr = 0;
    }

} ;

void update(char* c , Node * x)
{
    if(strlen(c) == 0)
    {
        x->N  ++;
        return;
    }

    if(x->sons[c[0]-'a'] != NULL)
    {
        update(c+1, x->sons[c[0]-'a']);
        return;
    }
    x->nr ++;
    x->sons[c[0]-'a'] = new Node();
    update(c+1, x->sons[c[0]-'a']);
}

bool del(char * c, Node *x)
{
    if(strlen(c) == 0)
    {
        if(x->N == 1 && x->nr == 0)
        {
            delete x;
            return true;
        }
        else x->N--;
        return false;

    }
    if(x->sons[c[0]-'a'] == NULL)
        return false;
    bool res = del(c+1, x->sons[c[0]-'a']);
    if(res)
    {
        x->sons[c[0]-'a'] = NULL;
        x->nr--;
        if(x -> nr == 0 && x -> N == 0)
        {
            delete x;
            return true;
        }
        return false;

    }
    return false;
}

int queryAp(char* c, Node* x)
{
    if(strlen(c) == 0)
        return x->N;
    if(x->sons[c[0]-'a'] == NULL)
        return 0;
    return queryAp(c+1, x->sons[c[0]-'a']);
}

int queryCMLP(char* c, Node* x)
{
    if(strlen(c) == 0)
        return 0;
    if(x->sons[c[0]-'a']!=NULL)
        return 1 + queryCMLP(c+1, x->sons[c[0]-'a']);
    return 0;
}

int main()
{
    int op;
    string s;
    char c[30];
    Node * T =new Node();
    while(fin>>op)
    {
        fin>>c;
        if(op == 0)
            update(c,T);
        else if(op == 1)
            del(c,T);
        else if(op == 2)
            fout<<queryAp(c,T)<<'\n';
        else fout<<queryCMLP(c,T)<<'\n';
    }



    fin.close();
    fout.close();
    return 0;
}