Cod sursa(job #2369470)

Utilizator HaesteinnSabau Florin Vlad Haesteinn Data 5 martie 2019 23:43:59
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.43 kb
#include <iostream>

#include <fstream>

#include <string>

using namespace std;



ifstream fin("trie.in");

ofstream fout("trie.out");



struct node

{

    int words=0;

    node* parent=0;

    node* edge[26]={};

}* root=new node;



int numberOfChildren(node* nod)

{

    int nr=0;

    for(int i=0;i<26;i++)

        if(nod->edge[i]!=NULL)

            nr++;

    return nr;

}



void addWord(string &w)

{

    node* crawler=root;

    for(int i=0;i<w.length();i++)

    {

        if(crawler->edge[w[i]-'a']==NULL)

        {

            node* element=new node;

            crawler->edge[w[i]-'a']=element;

            element->parent=crawler;

        }

        crawler=crawler->edge[w[i]-'a'];

    }

    crawler->words++;

}



int checkWord(string &w)

{

    node* crawler=root;

    for(int i=0;i<w.length()&&crawler!=NULL;i++)

        crawler=crawler->edge[w[i]-'a'];

    if(crawler!=NULL)

        return crawler->words;

    else return 0;

}



void deleteWord(string &w)

{

    node* crawler=root;

    for(int i=0;i<w.length();i++)

        crawler=crawler->edge[w[i]-'a'];

    crawler->words--;

    for(int i=w.length()-1;i>=0;i--)

    {

        if(crawler->words>0||numberOfChildren(crawler)>0)

            break;

        node* tmp;

        tmp=crawler;

        crawler=crawler->parent;

        crawler->edge[w[i]-'a']=NULL;

        delete tmp;

    }

}



int longestPrefix(string &w)

{

    node* crawler=root;

    int maxPrefix=0;

    bool ok=1;

    for(int i=0;i<w.length();i++)

    {

        crawler=crawler->edge[w[i]-'a'];

        if(crawler==NULL)

            break;

        //cout<<numberOfChildren(crawler)<<" ";

        if(numberOfChildren(crawler)>0)

            maxPrefix=i+1;

        if(crawler->words>0)

            maxPrefix=i+1;

        //cout<<maxPrefix<<" ";



    }



    return maxPrefix;

}



int main()

{

    string w;

    int command;

    while(1)

    {

        fin>>command>>w;

        if(fin.eof())

            break;

        if(command==0)

            addWord(w);

        if(command==1)

            deleteWord(w);

        if(command==2)

            fout<<checkWord(w)<<"\n";

        if(command==3)

            fout<<longestPrefix(w)<<"\n";

    }

    return 0;

}