Cod sursa(job #2752355)

Utilizator EZ4ENCEAleksi Jalli EZ4ENCE Data 17 mai 2021 19:19:40
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#define SIGMA 'z' - 'a' + 1

using namespace std;

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

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 poz) {
  root->freqpref++;
  if (poz == s.size()) {
    root->freqcuv++;
    return;
  }

  int lit = s[poz] - 'a';
  if (root->sons[lit] == NULL)
    root->sons[lit] = new Trie;
  add(root->sons[lit], s, poz + 1);
}

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

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

int cnt(Trie* root, string s, int poz) {
  if (poz == s.size())
    return root->freqcuv;

  int lit = s[poz] - 'a';
  return cnt(root->sons[lit], s, poz + 1);
}

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

  int lit = s[poz] - 'a';
  if (root->sons[lit] == NULL || root->sons[lit]->freqpref == 0)
    return poz;
  return pref(root-> sons[lit], s, poz + 1);
}

int main() {
  int op;
  Trie* root = new Trie();
  while (1) {
    string s;
    if (cin >> op) {
      cin >> 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 if (op == 3)
        cout << pref(root, s, 0) << "\n";
    }
    else
      return 0;
  }
  return 0;
}