Cod sursa(job #2902217)

Utilizator Teodor94Teodor Plop Teodor94 Data 15 mai 2022 21:37:01
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include <bits/stdc++.h>
using namespace std;

#define SIGMA 26
#define MAX_NODES 1000000

int noUsedNodes;

struct Node {
  static Node buffer[MAX_NODES];

  Node* edges[SIGMA];

  int noWords;
  int noFinalWords;

  inline Node* getEdge(char c) {
    return edges[c - 'a'] ? edges[c - 'a'] : NULL;
  }

  inline Node* addEdge(char c) {
    if (!edges[c - 'a'])
      edges[c - 'a'] = &buffer[noUsedNodes++];

    ++edges[c - 'a']->noWords;

    return edges[c - 'a'];
  }

  inline Node* removeEdge(char c) {
    --edges[c - 'a']->noWords;
    return edges[c - 'a'];
  }
};

Node Node::buffer[MAX_NODES];
Node root;

void addWord(const char* word) {
  int i;
  Node* current;

  i = 0;
  current = &root;
  while (word[i])
    current = current->addEdge(word[i++]);

  ++root.noWords;
  ++current->noFinalWords;
}

void removeWord(const char* word) {
  int i;
  Node* current;

  i = 0;
  current = &root;
  while (word[i] && current && current->noWords)
    current = current->getEdge(word[i++]);

  if (current && current->noFinalWords) {
    i = 0;
    current = &root;
    while (word[i])
      current = current->removeEdge(word[i++]);

    --root.noWords;
    --current->noFinalWords;
  }
}

int countWord(const char* word) {
  int i;
  Node* current;

  i = 0;
  current = &root;
  while (word[i] && current && current->noWords)
    current = current->getEdge(word[i++]);

  return current ? current->noFinalWords : 0;
}

int prefixLength(const char* word) {
  int i;
  Node* current;

  i = 0;
  current = &root;
  while (word[i] && current && current->noWords)
    current = current->getEdge(word[i++]);

  return current && current->noWords ? i : i - 1;
}

#define WORD_LENGTH 20
char word[WORD_LENGTH + 1];

int main() {
  FILE *fin, *fout;
  fin = fopen("trie.in", "r");
  fout = fopen("trie.out", "w");

  int op;
  while (fscanf(fin, "%d %s\n", &op, word) == 2) {
    if (op == 0)
      addWord(word);
    else if (op == 1)
      removeWord(word);
    else if (op == 2)
      fprintf(fout, "%d\n", countWord(word));
    else
      fprintf(fout, "%d\n", prefixLength(word));
  }

  fclose(fin);
  fclose(fout);
  return 0;
}