Cod sursa(job #2541724)

Utilizator rapunzelMihnea Andreescu rapunzel Data 8 februarie 2020 19:43:24
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>

using namespace std;

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

struct trie {
  int c1;
  int c2;
  trie *kids[26];
  trie() {
    c1 = c2 = 0;
    for (int i = 0; i < 26; i++) {
      kids[i] = 0;
    }
  }
};

trie *root = new trie;

void ins(string s) {
  trie *cur = root;
  for (auto &c : s) {
    int x = c - 'a';
    if (!cur -> kids[x]) {
      cur->kids[x] = new trie;
    }
    cur = cur->kids[x];
    cur->c2++;
  }
  cur->c1++;
}

void del(string s) {
  trie *cur = root;
  for (auto &c : s) {
    int x = c - 'a';
    cur = cur->kids[x];
    cur->c2--;
  }
  cur->c1--;
}

int s1(string s) {
  trie *cur = root;
  for (auto &c : s) {
    int x = c - 'a';
    if (!cur->kids[x]) {
      return 0;
    }
    cur = cur->kids[x];
  }
  return cur->c1;
}

int s2(string s) {
  int sol = 0;
  trie *cur = root;
  for (auto &c : s) {
    int x = c - 'a';
    if (!cur->kids[x] || !cur->kids[x]->c2) {
      return sol;
    }
    sol++;
    cur = cur->kids[x];
  }
  return sol;
}

int main() {
  int tp;
  string s;
  while (cin >> tp >> s) {
    if (tp == 0) {
      ins(s);
    }
    if (tp == 1) {
      del(s);
    }
    if (tp == 2) {
      cout << s1(s) << "\n";
    }
    if (tp == 3) {
      cout << s2(s) << "\n";
    }
  }

}