Cod sursa(job #2902395)

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

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

using namespace std;

struct node{
  char val;
  int nrWordsThatEndHere, depht, nrWords;
  int v[26];
};

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

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

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

  i = 0;
  currentNode = 0;
  while ( i < wordSize ) {
    if ( !tree[currentNode].v[word[i] - 'a'] )
      createEdge(currentNode, word[i], i + 1);

    currentNode = tree[currentNode].v[word[i] - 'a'];
    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].v[word[i] - 'a'] && tree[tree[currentNode].v[word[i] - 'a']].nrWords > 0 ) {
      currentNode = tree[currentNode].v[word[i] - 'a'];
      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;
}