Cod sursa(job #944723)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 29 aprilie 2013 16:33:13
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <vector>
#include <string.h>

using namespace std;

ifstream cin("trie.in");
ofstream cout("trie.out");

struct nod {
    long v[27], nr, nctr;
    void init()
    {
        for (char ii='a';ii!='z';ii++)
            v[ii-'a']=0;
    }
};
char s[25];
nod ng;
//trie
vector <nod> tr;

short op;
long ls, y;
void adauga(long x, long poz)
{
    if(poz == ls)
        tr[x].nr++;
    else
    {
        y=tr[x].v[s[poz]-'a'];
        if (y==0)
        {
            y=tr.size();
            tr.push_back(ng);
        }
        tr[x].v[s[poz]-'a']=y;
        adauga(y,poz+1);
    }
    tr[x].nctr++;
}

void sterge(long x, long poz)
{
    if (poz==ls)
        tr[x].nr--;
    else
    {
        y=tr[x].v[s[poz]-'a'];
        sterge(y,poz+1);
    }
    tr[x].nctr--;
}

void query1(long x, long poz)
{
    if (poz==ls)
        cout<<tr[x].nr<<'\n';
    else
    {
        y=tr[x].v[s[poz]-'a'];
        if (y==0)
            cout<<"0\n";
        else
            query1(y,poz+1);
    }
}

void query2(long x, long poz)
{
    if (poz==ls)
        cout<<poz<<"\n";
    else
    {
        y=tr[x].v[s[poz]-'a'];
        if ((y==0)||(tr[y].nctr==0))
            cout<<poz<<"\n";
        else
            query2(y,poz+1);
    }
}
int main()
{
    tr.push_back(ng);
    tr.push_back(ng);
    tr[0].nctr=tr[1].nctr=1;
    while(!cin.eof())
    {
        cin>>op>>s;
        ls=strlen(s);
        if(op == 0)
            adauga(1, 0);
        else if(op == 1)
                sterge(1, 0);
            else if(op == 2)
                query1(1, 0);
                else query2(1, 0);
    }
    cin.close();
    cout.close();
    return 0;
}