Cod sursa(job #2579513)

Utilizator stormy_weatherelena cristina stormy_weather Data 12 martie 2020 15:40:54
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb
#include<fstream>
#include<iostream>
#include<vector>
using namespace std;

struct trie {
  int nr_words, nr_sons;
  vector <trie*> sons;
  trie() {
    nr_words = 0;
    nr_sons = 0;
    sons = vector <trie*>(26, 0);
  }
};

void display_oper(vector <pair <int, string>> &oper) {
  for (int i = 0; i < (int) oper.size(); i++)
    cout << oper[i].first << " " << oper[i].second << "\n";
}

void add_word(trie* t, string &s, int pos) {
  if (pos == (int) s.size()) {
    t->nr_words++;
    return;
  }
  int c = s[pos] - 'a';
  if (t->sons[c] == 0) {
    t->sons[c] = new trie();
    t->nr_sons++;
  }
  add_word(t->sons[c], s, pos + 1);
}

int delete_word(trie* t, string &s, int pos, const trie* root) {
  if (pos == (int) s.size()) {
    t->nr_words--;
  } else {
    int c = s[pos] - 'a';
    int is_total_delete = delete_word(t->sons[c], s, pos + 1, root);
    if (is_total_delete == 1) {
      t->sons[c] = 0;
      t->nr_sons--;
    }
  }

  if (t->nr_words == 0 && t->nr_sons == 0 && t != root) {
    delete t;
    return 1;
  }
  return 0;
}

int count_word(trie* t, string &s, int pos) {
  if (pos == (int) s.size())
    return t->nr_words;
  int c = s[pos] - 'a';
  if (t->sons[c] == 0)
    return 0;
  return count_word(t->sons[c], s, pos + 1);
}

int find_prefix(trie *t, string &s, int pos, int count) {
  if (pos == (int) s.size()) {
    return count;
  }
  int c = s[pos] - 'a';
  if (t->sons[c] == 0) {
    return count;
  }

  return find_prefix(t->sons[c], s, pos + 1, count + 1);
}

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

  vector <pair <int, string>> oper;
  while(true) {
    int code; fin >> code;
    string word; fin >> word;
    if (fin.eof())
      break;
    oper.push_back({code, word});
  }

  // display_oper(oper);

  trie* t;
  t = new trie();

  for (int i = 0; i < (int) oper.size(); i++) {
    if (oper[i].first == 0) {
      add_word(t, oper[i].second, 0);
    } else if (oper[i].first == 1) {
      delete_word(t, oper[i].second, 0, t);
    } else if (oper[i].first == 2) {
      fout << count_word(t, oper[i].second, 0) << "\n";
    } else if (oper[i].first == 3) {
      fout << find_prefix(t, oper[i].second, 0, 0) << "\n";
    }
  }

  return 0;
}