Cod sursa(job #2902393)

Utilizator iraresmihaiiordache rares mihai iraresmihai Data 16 mai 2022 09:38:38
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb
#include <iostream>
#include <string.h>
#include <unordered_map>

#define MAXN 2000000
#define MAX_SIZE 20
#define INF 30

using namespace std;

struct node{
  char val;
  int nrWordsThatEndHere, depht, nrWords;
  unordered_map <char, int> edges;
};

node tree[MAXN + 1];
int treeSize;
int word[MAX_SIZE];
int wordSize;

void createEdge(int posInTree, char val, int depht) {
  tree[posInTree].edges[val] = treeSize;
  tree[treeSize].depht = depht;
  treeSize++;
}

void goToWord01(int valToAdd) {
  int i, currentNode;

  i = 0;
  currentNode = 0;
  while ( i < wordSize ) {
    if ( tree[currentNode].edges.find(word[i]) == tree[currentNode].edges.end() )
      createEdge(currentNode, word[i], i + 1);

    currentNode = tree[currentNode].edges[word[i]];
    tree[currentNode].nrWords += valToAdd;
    if ( i == wordSize - 1 )
      tree[currentNode].nrWordsThatEndHere += valToAdd;
    i++;
  }
}

int goToWord23() {
  int i, currentNode;

  i = 0;
  currentNode = 0;
  while ( i < wordSize ) {
    if ( tree[currentNode].edges.find(word[i]) != tree[currentNode].edges.end() && tree[tree[currentNode].edges[word[i]]].nrWords > 0 ) {
      currentNode = tree[currentNode].edges[word[i]];
      i++;
    } else {
      i = INF;
    }
  }

  return currentNode;
}

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

  char i, ch2;
  int nodePos;

  treeSize = 1;

  i = fgetc(fin);
  while ( i >= '0' && i <= '3' ) {
    fgetc(fin);

    wordSize = 0;
    ch2 = fgetc(fin);
    while ( 'a' <= ch2 && ch2 <= 'z' ) {
      word[wordSize] = ch2;
      wordSize++;
      ch2 = fgetc(fin);
    }

    i -= '0';
    if ( i == 0 ) {
      goToWord01(1);
    } else if ( i == 1 ) {
      goToWord01(-1);
    } else if ( i == 2 ) {
      nodePos = goToWord23();
      if ( tree[nodePos].depht == wordSize )
        fprintf(fout, "%d\n", tree[nodePos].nrWordsThatEndHere);
      else
        fprintf(fout, "0\n");
    } else {
      nodePos = goToWord23();
      fprintf(fout, "%d\n", tree[nodePos].depht);
    }
    i = fgetc(fin);
  }

  fclose(fin);
  fclose(fout);

  return 0;
}