Cod sursa(job #2289742)

Utilizator cc4infinityCojocaru Catalin cc4infinity Data 25 noiembrie 2018 11:00:19
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb

#include <bits/stdc++.h>

using namespace std;

struct trie
{
    struct trie *copil[30];
    struct trie *tata;
    int eow;
    int rang;
    trie()
    {
        rang=0;
        tata=NULL;
        eow=0;
        for (int i=0;i<=27;i++)
        copil[i]=NULL;
    }
};

/*struct trie *creaza(void)
{
    struct trie  *tnode=new trie;
    tnode->rang=0;
    tnode->eow=0;
    for (int i=0;i<=27;i++)
        tnode->copil[i]=NULL;
    return tnode;
};*/
string s;


void insert(string s,trie *curent)
{
    for (int i=0;i<s.size();i++)
    {
        int n=s[i]-'a';
        if (!curent->copil[n])
            {curent->copil[n]=new trie;
             curent->rang++;
             curent->copil[n]->tata=curent;
             }
        curent=curent->copil[n];
    }
    curent->eow++;
}

int apare(string s,trie *curent)
{
    for (int i=0;i<s.size();i++)
    {
        int n=s[i]-'a';
        if (curent->copil[n]==NULL)
            return 0;
        curent=curent->copil[n];
    }
    return curent->eow;
}

int pref(string s,trie *curent)
{
    for (int i=0;i<s.size();i++)
    {
        int n=s[i]-'a';
        if (!curent->copil[n])
            return i;
        curent=curent->copil[n];
    }
    return s.size();
}

bool sterge(int l,struct trie *nod)
{
    if (l==s.size()-1)
    {
        nod->eow--;
        if (nod->rang) {return 0; nod->eow--;}
        else {
              // delete nod;
              nod=NULL;
              return 1;}
    }
    int n=s[l+1]-'a';
    if (sterge(l+1,nod->copil[n]))
    {
        nod->copil[n]=NULL;
        if (nod->rang>1) {nod->rang--; return 0;}
        //if (nod->eow) {nod->eow--; return 0;}
        //delete nod;
        nod=NULL;
        return 1;
    }
}

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

int i,j,m,n,a,b;

trie *root=new trie;
int main()
{
    while (!fin.eof())
    {
        fin>>i>>s;
        if (fin.eof()) break;
        if (i==0) insert(s,root);
        if (i==1) b=sterge(0,root->copil[s[0]-'a']);
        if (i==2) fout<<apare(s,root)<<"\n";
        if (i==3) fout<<pref(s,root)<<"\n";
    }
    return 0;
}