Cod sursa(job #1622465)

Utilizator andreimdvMoldovan Andrei andreimdv Data 1 martie 2016 11:44:11
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include<cstring>
using namespace std;

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

struct nod{
    int trecutaici;
    int terminataici;
    nod * v[26];
    nod()
    {
        trecutaici=terminataici=0;
        for(int i=0;i<26;++i)
        v[i]=NULL;
    }
} *arb,*p;


int n,t,i,j;
char s[30];

void adauga()
{
    p=arb;
    int c;
    int len=strlen(s);
    for(int i=0;i<len;++i)
    {
        c=s[i]-'a';
        if(p->v[c]==NULL)
        {
            p->v[c]=new nod();
        }
        p=p->v[c];
        p->trecutaici++;
        if(i==len-1)
        p->terminataici++;
    }
}
void sterge()
{
    p=arb;
    int c;
    int len=strlen(s);
    for(int i=0;i<len;++i)
    {
        c=s[i]-'a';
        p=p->v[c];
        p->trecutaici--;
        if(i==len-1)
        p->terminataici--;
       // if(p->trecutaici==0)
      //  delete(p);
    }
}
void tipareste()
{
    p=arb;
    int c;
    int len=strlen(s);
    for(int i=0;i<len;++i)
    {
        c=s[i]-'a';
        if(p->v[c]==NULL||p->v[c]->trecutaici==0)
        {
            fout<<0<<'\n';
            return;
        }
        else
        p=p->v[c];
    }
    fout<<p->terminataici<<'\n';
}

void prefix()
{
    p=arb;
    int c;
    int i;
    int len=strlen(s);
    for(i=0;i<len;++i)
    {
        c=s[i]-'a';
        if(p->v[c]==NULL||p->v[c]->trecutaici==0)
        {
            fout<<i<<'\n';
            return;
        }
        else
        {
            p=p->v[c];
        }
    }
}



int main()
{
    arb=new nod();
    while(fin>>t)
    {
        fin>>s;
        if(t==0)
        adauga();
        if(t==1)
        sterge();
        if(t==2)
        tipareste();
        if(t==3)
        prefix();
    }

    return 0;
}