Cod sursa(job #3204749)

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

using namespace std;

struct TrieNode {
  map<char, TrieNode*> children;
  int count;

  TrieNode() {
    count = 0;
  }
};

class Trie {
  TrieNode *root;

public:
  Trie() {
    root = new TrieNode();
  }

  void insert(string word) {
    TrieNode *current = root;
    for (char c : word) {
      if (!current->children.count(c)) {
        current->children[c] = new TrieNode();
      }
      current = current->children[c];
    }
    current->count++;
  }

  int find(string word) {
    TrieNode *current = root;
    for (char c : word) {
      if (!current->children.count(c)) {
        return 0;
      }
      current = current->children[c];
    }
    return current->count;
  }

  int longestCommonPrefix(string word) {
    TrieNode *current = root;
    int prefix_length = 0;
    for (char c : word) {
      if (!current->children.count(c)) {
        break;
      }
      current = current->children[c];
      prefix_length++;
    }
    return prefix_length;
  }
};

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

  Trie trie;

  int n;
  in >> n;

  for (int i = 0; i < n; i++) {
    int op;
    string word;
    in >> op >> word;

    switch (op) {
      case 0:
        trie.insert(word);
        break;
      case 1:
        trie.find(word);
        break;
      case 2:
        out << trie.find(word) << endl;
        break;
      case 3:
        out << trie.longestCommonPrefix(word) << endl;
        break;
    }
  }

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

  return 0;
}