Cod sursa(job #2417887)

Utilizator ApolodorTudor Fernea Apolodor Data 2 mai 2019 00:07:06
Problema Trie Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <vector>
#include <cstring>
#include <fstream>

using namespace std;

ifstream fi("trie.in");
ofstream fo("trie.out");

int t,w;
string s;

struct trie{
    int k,nrch;
    trie *child[26];

    trie()
    {
        k=nrch=0;
        memset(child,0,sizeof(child));
    }

};

trie *T=new trie;

void push(trie *nod, int poz, string ss)
{
    if(poz==ss.size())
    {
        nod->k++;
        return;
    }

    if(nod->child[ss[poz]-'a']==NULL)
    {
        nod->child[ss[poz]-'a']=new trie;
        nod->nrch++;
    }

    push(nod->child[ss[poz]-'a'], poz+1, ss);

}

int pop(trie *nod, int poz, string ss)
{
    if(poz==ss.size())
        nod->k--;
    else if(pop(nod->child[ss[poz]-'a'], poz+1, ss))
    {
        nod->nrch--;
        nod->child[ss[poz]-'a']=NULL;
    }

    if(nod->nrch==0 && nod->k==0 && nod!=T)
    {
        delete nod;
        return 1;
    }

    return 0;

}

int que(trie *nod, int poz, string ss)
{
    if(poz==ss.size())
        return nod->k;

    if(nod->child[ss[poz]-'a'])
        return que(nod->child[ss[poz]-'a'], poz+1, ss);

    return 0;
}

int pref(trie *nod, int poz, string ss)
{
    if(poz==ss.size() || nod->child[ss[poz]-'a']==NULL)
        return poz;

    return pref(nod->child[ss[poz]-'a'], poz+1, ss);

}

int main()
{

    while(fi>>w>>s)
    {
        if(w==0)
            push(T,0,s);
        if(w==1)
            pop(T,0,s);
        if(w==2)
            fo<<que(T,0,s)<<'\n';
        if(w==3)
            fo<<pref(T,0,s)<<'\n';

    }

    return 0;
}