Cod sursa(job #2838068)

Utilizator GrizzyProblemSolver79cNot telling GrizzyProblemSolver79c Data 23 ianuarie 2022 01:11:04
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream in("trie.in");
ofstream out("trie.out");

struct Trie {
  int pr;
    // the number of words that have root-node as a prefix        <=>
    // the number of words that end somewhere in the node subtree

  Trie* sons[26];
};

Trie* t = new Trie();


//m, o, t,  h, e, r, \0, !, ?,
//c, a, t, \0, e, r, \0, !, ?,
//in this implementation of trie, there is this quiet assumption that t != NULL
void add(Trie* t, char *s) {
  t -> pr++;
  if(*s != '\0') {
    int c = *s - 'a';
    if(t->sons[c] == NULL) {
      t->sons[c] = new Trie();
    }
    add(t->sons[c], s+1);
  }
}

void del(Trie* t, char *s) {
  t -> pr--;
  if(*s != '\0') {
    int c = *s - 'a';
    del(t->sons[c], s+1); //lazy delete
  }
}

int numApp(Trie* t, char *s) {
  if(*s == '\0') {
    int ans = t->pr;
    for(int i = 0; i < 26; i++) {
      if(t->sons[i] != NULL) {
        ans -= t->sons[i]->pr;
      }
    }
    return ans;
  } else {
    int c = *s - 'a';
    if(t->sons[c] == NULL || t->sons[c]->pr == 0) {
      return 0;
    }
    return numApp(t->sons[c], s+1);
  }
}

int lcp(Trie* t, char *s, int ans) {
  if(*s == '\0') {
    return ans;
  } else {
    int c = *s - 'a';
    if(t->sons[c] == NULL || t->sons[c]->pr == 0) {
      return ans;
    }
    return lcp(t->sons[c], s+1, ans+1);
  }
}

int main() {
  int type;
  string word;

  while(in >> type >> word) {
    if(type == 0) {
      add(t, &(word[0]) );
    } else if(type == 1) {
      del(t, &(word[0]) );
    } else if(type == 2) {
      out << numApp(t, &(word[0]) ) << "\n";
    } else {
      out << lcp(t, &(word[0]), 0) << "\n";
    }
  }
  return 0;
}