Cod sursa(job #2636240)

Utilizator isa_tudor_andreiAndrei Tudor isa_tudor_andrei Data 17 iulie 2020 12:56:29
Problema Trie Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <cstdio>
#include <cstring>

using namespace std;

struct Trie{
  int nrfii, cnt;
  Trie* fiu[26];

  Trie () {
    nrfii = cnt = 0;
    memset(fiu, 0, sizeof(fiu));
  }
};

Trie *root = new Trie;

void ins( Trie* node, char *s ) {
  if( *s == '\n' ) {
    node->cnt ++;
    return ;
  }
  int ch = *s - 'a';
  if( node->fiu[ch] == 0 ) {
    node->fiu[ch] = new Trie;
    node->nrfii ++;
  }
  ins(node->fiu[ch], s + 1);
}

bool del( Trie* node, char *s ) {
  int ch = *s - 'a';
  if( *s == '\n' ) {
    node->cnt --;
  }
  else if( del(node->fiu[ch], s + 1) ) {
    node->fiu[ch] = 0;
    node->nrfii --;
  }
  if( node->nrfii == 0 && node->cnt == 0 && node != root ) {
    delete node;
    return true;
  }
  return false;
}

int ap( Trie* node, char* s ) {
  if( *s == '\n' )
    return node->cnt;
  int ch = *s - 'a';
  if( node->fiu[ch] != 0 )
    return ap(node->fiu[ch], s + 1);

  return 0;
}

int prefix( Trie* node, char* s ) {
  int ch = *s - 'a';
  if( node->fiu[ch] == 0 )
    return 0;
  return 1 + prefix(node->fiu[ch], s + 1);
}

int main() {
	freopen( "trie.in", "r", stdin );
	freopen( "trie.out", "w", stdout );

  char line[32];
  fgets( line, 32, stdin );

	while( !feof( stdin ) ) {
		switch( line[0] ) {
			case '0': ins( root, line+2 ); break;
			case '1': del( root, line+2 ); break;
			case '2': printf("%d\n", ap( root, line+2 )); break;
			case '3': printf("%d\n", prefix( root, line+2)); break;
		}

		fgets( line, 32, stdin );
	}
  return 0;
}