Cod sursa(job #1165093)

Utilizator lianaliana tucar liana Data 2 aprilie 2014 14:21:10
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include<stdio.h>
#include<vector>
#include<cstring>
using namespace std;
#define lgmax 30
struct nod{int ncuv, npref, v['z'-'a'+2];
    void init()
    {
        for (char c='a';c<='z';c++)
            v[c]=0;
    }
};
int op, ls;
char s[lgmax];
nod ng;
vector <nod> tr;

void adauga(int nod, int poz)
{
    if (poz==ls)
        tr[nod].ncuv++;
    else
    {
        if (tr[nod].v[s[poz]-'a']==0)
        {
            tr.push_back(ng);
            tr[nod].v[s[poz]-'a']=tr.size()-1;

        }
        adauga(tr[nod].v[s[poz]-'a'],poz+1);
    }
    tr[nod].npref++;
}

void sterge(int nod, int poz)
{
    if (poz==ls)
        tr[nod].ncuv--;
    else
        sterge(tr[nod].v[s[poz]-'a'],poz+1);
    tr[nod].npref--;
}

void query1(int nod, int poz)
{
    if (poz==ls)
        printf("%ld\n",tr[nod].ncuv);
    else
    {
        if ((tr[nod].v[s[poz]-'a']==0)||(tr[nod].npref==0))
            printf("0\n");
        else
            query1(tr[nod].v[s[poz]-'a'],poz+1);
    }
}

void query2(int nod, int poz)
{
    if (poz==ls)
        printf("%ld\n",poz);
    else
    {
        if ((tr[nod].v[s[poz]-'a']==0)||(tr[tr[nod].v[s[poz]-'a']].npref==0))
            printf("%ld\n",poz);
        else
            query2(tr[nod].v[s[poz]-'a'],poz+1);
    }
}

int main()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    tr.push_back(ng);
    while(scanf("%ld %s",&op,&s)==2)
    {
        ls=strlen(s);
        if (op==0)
            adauga(0,0);
        if (op==1)
            sterge(0,0);
        if (op==2)
            query1(0,0);
        if (op==3)
            query2(0,0);
    }
    return 0;
}