Cod sursa(job #3204758)

Utilizator marius135Dumitran Adrian Marius marius135 Data 17 februarie 2024 13:17:41
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

struct TrieNode {
  bool is_word;
  int count;
  TrieNode *children[26];

  TrieNode() {
    is_word = false;
    count = 0;
    for (int i = 0; i < 26; i++) {
      children[i] = nullptr;
    }
  }
};

void insert(TrieNode *root, string word) {
  for (char c : word) {
    int index = c - 'a';
    if (root->children[index] == nullptr) {
      root->children[index] = new TrieNode();
    }
    root = root->children[index];
  }
  root->is_word = true;
  root->count++;
}

int find_count(TrieNode *root, string word) {
  for (char c : word) {
    int index = c - 'a';
    if (root->children[index] == nullptr) {
      return 0;
    }
    root = root->children[index];
  }
  return root->count;
}

int find_longest_prefix(TrieNode *root, string word) {
  int longest_prefix = 0;
  TrieNode *current = root;

  for (char c : word) {
    int index = c - 'a';
    if (current->children[index] == nullptr) {
      break;
    }
    current = current->children[index];
    longest_prefix++;
  }

  if (current->is_word) {
    longest_prefix = max(longest_prefix, (int)word.length());
  }

  return longest_prefix;
}

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

  TrieNode *root = new TrieNode();

  int n;
  in >> n;

  while (n--) {
    int op;
    string word;
    in >> op >> word;

    switch (op) {
      case 0:
        insert(root, word);
        break;
      case 1:
        if (find_count(root, word) > 0) {
          insert(root, word);
        }
        break;
      case 2:
        out << find_count(root, word) << endl;
        break;
      case 3:
        out << find_longest_prefix(root, word) << endl;
        break;
    }
  }

  in.close();
  out.close();

  return 0;
}