Cod sursa(job #1511505)

Utilizator Vlad_317Vlad Panait Vlad_317 Data 26 octombrie 2015 20:28:20
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <stdio.h>

using namespace std;

#define CH (*s - 'a')


class trie
{
public:
    trie *v[26];
    int cnt;
    int nr;
    int nrcuv;
    trie()
    {
        cnt = 0;
        nr = 0;
        nrcuv = 0;
        for(int i = 0; i <= 25; ++i)
            v[i] = NULL;
    }
    void ins(char *s)
    {
        if(*s == NULL)
        {
            this->cnt++;
            return;
        }
        else
        {
            if(this->v[CH] == NULL)
            {
                this->v[CH] = new trie;
                this->nr++;
            }
        }
        this->v[CH]->ins(s+1);
    }
    bool del( char *s)
    {
        if(*s == NULL)
        {
            this->cnt--;
        }
        else if( this->v[ CH ]->del(s+1) )
        {
            delete this->v[CH];
            this->v[ CH ] = 0;
            this->nr --;

        }

        if( this->cnt == 0 && this->nr == 0 )
        {
            return 1;
        }

        return 0;
    }
    int que( char *s)
    {
        if(*s == NULL)
            return this->cnt;
        else
        {
            if(this -> v[CH])
                return this->v[CH]->que(s+1);
            else
                return 0;
        }
    }
    int pre( char *s, int k)
    {
        if(*s == NULL || this->v[CH]==0)
            return k;
        return this->v[CH]->pre(s+1, k+1);
    }
};


trie *nod = new trie;

int main()
{
    FILE *fin, *fout;

    fin=fopen("trie.in","r");
    fout=fopen("trie.out","w");

    int x;

    while(fscanf(fin,"%d ",&x)!=EOF)
    {
        char s[21];
        fscanf(fin,"%s",s);
        if(x==0)
            nod->ins(s);
        if(x==1)
            nod->del(s);
        if(x==2)
            fprintf(fout,"%d\n",nod->que(s));
        if(x==3)
            fprintf(fout,"%d\n",nod->pre(s, 0));
    }
    return 0;
}