Cod sursa(job #2483228)

Utilizator andrei42Oandrei42O andrei42O Data 29 octombrie 2019 15:49:09
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.6 kb
#include <bits/stdc++.h>
#define pos first
#define val second
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct nod
{
    int P,C;/// P = cate cuvinte parcurg nodul C = Cate cuvinte se termina in nod
    nod *S[26];
    nod()
    {
        P=C=0;
        for(int i=0; i<26; i++)
            S[i]=NULL;
    }
};
inline int nr(char c)
{
    int ret=c-'a';
    return ret;
}
nod *root,*q[25];
char w[25];
inline int prefix()
{
    int ret=0;
    nod *x=root;
    char *y=w;
    for(; y; y++)
    {
        int i=nr(*y);
        if(x->S[i])
        {
            ret++;
            x=x->S[i];
        }
        else return ret;
    }
    return ret;
}
inline int aparitii()
{
    nod *x=root;
    char *y=w;
    for(; y; y++)
    {
        int i=nr(*y);
        if(x->S[i])x=x->S[i];
        else return 0;
    }
    return x->C;
}
int Lg,cod;
void coada()
{
    Lg=0;
    q[0]=root;
    nod *x=root;
    char *y=w;
    for(; y; y++)
    {
        int i=nr(*y);
        if(!x->S[i])x->S[i]=new nod;
        x=x->S[i];
        q[++Lg]=x;
    }
}
int main()
{
    root=new nod;
    while(f>>cod)
    {
        f>>w;
        if(cod==3)
        {
            int pr=0;
            nod *r=root;
            for(char *p=w; *p; p++)
            {
                int j=nr(*p);
                if(!r->S[j])
                    break;
                r=r->S[j];
                if(r->P+r->C==0)
                    break;
                pr++;
            }
            g<<pr<<'\n';
            continue;
        }
        if(cod==2)
        {
            int ap=0;
            char *p;
            nod *r=root;
            for(p=w; *p; p++)
            {
                int j=nr(*p);
                if(!r->S[j])
                    break;
                r=r->S[j];
            }
            if(*p)
                ap=0;
            else
                ap=r->C;
            g<<ap<<'\n';
            continue;
        }
        if(cod==0)
        {
            nod *r=root;
            char *p;
            for(p=w; *p; p++)
            {
                r->P++;
                int j=nr(*p);
                if(!r->S[j])
                    r->S[j]=new nod;
                r=r->S[j];
            }
            r->C++;
            continue;
        }
        nod *r=root;
        char *p;
        for(p=w; *p; p++)
        {
            r->P--;
            int j=nr(*p);
            if(!r->S[j])
                r->S[j]=new nod;
            r=r->S[j];
        }
        r->C--;


    }
    return 0;
}