Cod sursa(job #2018256)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 4 septembrie 2017 10:04:56
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;
ifstream in ("trie.in");
ofstream out ("trie.out");

int const litmax = 26;
int const nmax = 20;

struct Trie {
  int pref; //din cate cuvinte face parte prefixul pana in acest nod
  Trie* vec[litmax];
};

Trie* root;

void addtrie(Trie* node, char* word) {
  node->pref++;
  //cout<<"A "<<node->pref<<" "<<word<<'\n';

  if(*word != '\0') {
    int pos = *word - 'a';
    if(node->vec[pos] == NULL) //nullptr
      node->vec[pos] = new Trie();
    addtrie(node->vec[pos] , word + 1);
  }
}

void deltrie(Trie* node , char* word) {
  //cout<<"D "<<node->pref<<" "<<word<<'\n';
  node->pref--;
  //cout<<"D "<<node->pref<<" "<<word<<'\n';

  if(*word != '\0') {
    int pos = *word - 'a';
    deltrie(node->vec[pos] , word + 1);
  }
}

int aparitii(Trie* node , char* word) {
  if(*word != '\0') {
    int pos = *word - 'a';
    if(node->vec[pos] == NULL)
      return 0;
    else
      return aparitii(node->vec[pos] , word + 1);
  } else {
    int answer = node->pref;
    for(int i = 0 ; i < litmax; i++) {
      if(node->vec[i] != NULL) {
        answer -= node->vec[i]->pref;
      }
    }
    return answer;
  }
}

int prefix(Trie* node, char* word, int lung = 0) {
  //cout<<*word<<" "<<lung<<" "<<node->pref<<'\n';
  if(*word != '\0' ) {
    int pos = *word - 'a';

    if(node->vec[pos] != NULL && 0 < node->vec[pos]->pref)
      return prefix(node->vec[pos], word + 1, lung + 1);
  }
  return lung;
}

int main() {
  char word[nmax + 4];
  int option;

  root = new Trie();
  root->pref = 0;

  while(in >> option && in >> word){
   // cout<<option<<" "<<word<<" "<<strlen(word)<<'\n';
    if(option == 0) {
      addtrie(root, word);
    } else if(option == 1) {
      deltrie(root, word);
    } else if(option == 2) {
      out<<aparitii(root, word)<<'\n';
    } else if(option == 3){
      out<<prefix(root , word )<<'\n';
    }
  }
  return 0;
}