Cod sursa(job #2623367)

Utilizator euyoTukanul euyo Data 3 iunie 2020 00:23:14
Problema Heapuri Scor 40
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <stdio.h>
#define MAXH 200000

struct H {
  int val;
  int t;
} heap[MAXH];

int p[MAXH];
int indH, time = 1;

static inline int fth( int node ) { //father
  return (node >> 1);
}
static inline int lSon( int node ) { //left son
  return ((node << 1) + 1);
}
static inline int rSon( int node ) { //right son
  return (node << 1);
}

void swap( int a, int b ) {
  int aux;

  aux = heap[a].val;
  heap[a].val = heap[b].val;
  heap[b].val = aux;
  aux = heap[a].t;
  heap[a].t = heap[b].t;
  heap[b].t = aux;
  p[heap[a].t] = a;
  p[heap[b].t] = b;
}

void repairUpp( int node ) {
  while ( node > 0 && heap[node].val < heap[fth( node )].val ) {
	swap( node, fth( node ) );
	node = fth( node );
  }
}
void repairDown( int node ) { 
  while ( node <= indH ) {
    if ( heap[lSon( node )].val < heap[rSon( node )].val ) {
      if ( heap[lSon( node )].val < heap[node].val ) {
        if ( lSon( node ) <= indH ) {
		  swap( lSon( node ), node );
	      node = lSon( node );
		} else {
		  node = indH + 1;
		}
	  } else {
		node = indH + 1;
	  }
	} else {
	  if ( heap[rSon( node )].val < heap[node].val ) {
		if ( rSon( node ) <= indH ) {
		  swap( rSon( node ), node );
		  node = rSon( node );
		} else {
		  node = indH + 1;
		}
	  } else {
        node = indH + 1;
	  }
	}
  }
}
void add( int value ) {
  p[time++] = ++indH;
  heap[indH].val = value;
  heap[indH].t = time - 1;
  repairUpp( indH );
}
void cut( int t ) {
  int node = p[t];
  
  swap( indH, node );
  --indH;
  repairDown( node );
  repairUpp( indH );
}


int main() {
  FILE *fin = fopen( "heapuri.in", "r" );
  FILE *fout = fopen( "heapuri.out" , "w" );
  int n, i, type, x;
  
  fscanf( fin, "%d", &n );
  for ( i = 0; i < n; ++i ) {
	fscanf( fin, "%d", &type );
	switch ( type ) {
	case 1:
	  fscanf( fin, "%d", &x );
	  add( x );
	  break;
    case 2:
      fscanf( fin, "%d", &x );
      cut( x );
	  break;
	case 3:
      fprintf( fout, "%d\n", heap[1].val );	   
	  break;
	}
  }
  fclose( fin );
  fclose( fout );
  return 0;
}