Cod sursa(job #2788439)

Utilizator YusyBossFares Yusuf YusyBoss Data 25 octombrie 2021 18:04:29
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#define SIGMA 26

using namespace std;

ifstream cin ("trie.in");
ofstream cout ("trie.out");

struct strnode {
  int finish_word, finish_prefix;
};

struct Trie {
  int freqpref, freqcuv;
  Trie* sons[SIGMA + 1];

  Trie() {
    freqpref = freqcuv = 0;
    for (int i = 0; i < SIGMA; ++i)
      sons[i] = NULL;
  }
};

void add(Trie* root, string s, int pos) {
  root->freqpref++;
  if (pos == s.size()) {
    root->freqcuv++;
    return;
  }
  int lit = s[pos] - 'a';
  if (root->sons[lit] == NULL)
    root->sons[lit] = new Trie;
  add(root->sons[lit], s, pos + 1);
}

void del(Trie* root, string s, int pos) {
  root-> freqpref--;
  if (pos == s.size()) {
    root->freqcuv--;
    return;
  }

  int lit = s[pos] - 'a';
  del(root-> sons[lit], s, pos + 1);
}

int cnt(Trie* root, string s, int pos) {
  if (pos == s.size())
    return root->freqcuv;
  int lit = s[pos] - 'a';
  if (root->sons[lit] == NULL || root->sons[lit]->freqpref == 0)
    return 0;
  return cnt(root -> sons[lit], s, pos + 1);
}

int pref(Trie* root, string s, int pos) {
  if (pos == s.size())
    return pos;

  int lit = s[pos] - 'a';
  if (root->sons[lit] == NULL || root->sons[lit]->freqpref == 0)
    return pos;

  return pref(root-> sons[lit], s, pos + 1);
}

int main() {
  Trie* root;
  int op;
  string s;

  root = new Trie;
  while (cin >> op >> s) {
    if (op == 0)
      add(root, s, 0);
    else if (op == 1)
      del(root, s, 0);
    else if (op == 2)
      cout << cnt(root, s, 0) << "\n";
    else
      cout << pref(root, s, 0) << "\n";
    s = "";
  }
  return 0;
}