Cod sursa(job #2842039)

Utilizator vlad2009Vlad Tutunaru vlad2009 Data 30 ianuarie 2022 22:42:34
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>
#include <iostream>

const int SIGMA = 26;

struct Trie {
  int freq;
  int words;
  Trie* children[SIGMA];

  Trie() {
    freq = 0;
    words = 0;
    for (int i = 0; i < SIGMA; i++) {
      children[i] = NULL;
    }
  }
};

void insert(Trie* root, char* S) {
  if (*S == '\0') {
    root->freq++;
    root->words++;
  } else {
    if (root->children[S[0] - 'a'] == NULL) {
      root->children[S[0] - 'a'] = new Trie();
    }
    root->children[S[0] - 'a']->freq++;
    insert(root->children[S[0] - 'a'], S + 1);
  }
}

void erase(Trie* root, char* S) {
  if (*S == '\0') {
    if (root->freq > 0) {
      root->freq--;
      root->words--;
    }
  } else {
    if (root->children[S[0] - 'a'] != NULL) {
      root->children[S[0] - 'a']->freq--;
      erase(root->children[S[0] - 'a'], S + 1);
    }
  }
}

int count(Trie* root, char* S) {
  if (*S == '\0') {
    return root->words;
  } else {
    if (root->children[S[0] - 'a'] == NULL || root->children[S[0] - 'a']->freq == 0) {
      return 0;
    }
    count(root->children[S[0] - 'a'], S + 1);
  }
}

int prefix(Trie* root, char* S, int cnt = 0) {
  if (*S == '\0') {
    return cnt;
  } else {
    if (root->children[S[0] - 'a'] != NULL && root->children[S[0] - 'a']->freq > 0) {
      prefix(root->children[S[0] - 'a'], S + 1, cnt + 1);
    } else {
      return cnt;
    }
  }
}

int main() {
  std::ifstream fin("trie.in");
  std::ofstream fout("trie.out");
  Trie root;
  char* S = new char[20 + 1];
  int t;
  while (fin >> t) {
    fin >> S;
    if (t == 0) {
      insert(&root, S);
    } else if (t == 1) {
      erase(&root, S);
    } else if (t == 2) {
      fout << count(&root, S) << "\n";
    } else {
      fout << prefix(&root, S) << "\n";
    }
  }
  return 0;
}