Cod sursa(job #2422366)

Utilizator MortemPlaiasu Iulia-Silvia Mortem Data 18 mai 2019 15:35:35
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>

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

char c[36];
int in;
char useless;

struct nod
{
  int pre=0;
  int app=0;
  nod* v[28]={NULL};
};

void push( nod* root,int ind)
{
  int ch = (int)(c[ind]-'a');
  if(root->v[ch]==NULL)
    root->v[ch]= new nod;
  root->v[ch]->pre++;
  if(c[ind+1]!='\0')
    push(root->v[ch],ind+1);
  else
    root->v[ch]->app++;
//  std::cout<<c<<" "<<(char)(ch+'a')<<" "<<root->v[ch]->pre<<" "<<root->v[ch]->app<<"\n";
}

void erase(nod* root, int ind)
{
  int ch = (int)(c[ind]-'a');
  root->v[ch]->pre--;
  if(c[ind+1]=='\0')
    root->v[ch]->app--;
  else
    erase(root->v[ch],ind+1);
  //std::cout<<c<<" "<<(char)(ch+'a')<<" "<<root->v[ch]->pre<<" "<<root->v[ch]->app<<"\n";
}

int find(nod *root, int ind)
{
  int ch = (int)(c[ind]-'a');
  if(c[ind+1]=='\0' && root->v[ch]!=NULL)
    return root->v[ch]->app;
  else if(root->v[ch]!=NULL)
    return find(root->v[ch],ind+1);
  else
    return 0;
}

int larg(nod *root, int ind, int countt)
{
  int ch=(int)(c[ind]-'a');
  if(c[ind+1]=='\0')
    return countt+1;
  else if(root->v[ch]!=NULL && root->v[ch]->pre!=0)
    return larg(root->v[ch],ind+1,countt+1);
  else
    return countt;
}

int main()
{
  nod * root = new nod;
  fin>>in;
  while(fin.getline(c,35))
  {
    //push
    if(in==0)
      push(root,1);
    //erase one
    else if(in==1)
      erase(root,1);
    //count appearances
    else if(in==2)
      fout<<find(root,1)<<"\n";
    //biggest prefix
    else
      fout<<larg(root,1,0)<<"\n";
    
    fin>>in;
  }
}