Cod sursa(job #2628430)

Utilizator euyoTukanul euyo Data 15 iunie 2020 21:45:44
Problema Heapuri Scor 30
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <stdio.h>
#define MAXH 200001

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;
}
static inline int rSon( int node ) { //right son
  return ((node << 1) + 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 > 1 && heap[node].val < heap[fth( node )].val ) {
	swap( node, fth( node ) );
	node = fth( node );
  }
}
void repairDown( int node ) { 
  int son;

  while ( node < indH ) {
	if ( lSon( node ) <= indH && rSon( node ) <= indH ) {
      if ( heap[lSon( node )].val < heap[rSon( node )].val ) {
        son = lSon( node );
	  } else {
		son = rSon( node );
	  }
	} else if ( lSon( node ) > indH ) {
	  son = rSon( node );
	} else {
	  son = lSon( node );
	}
    if ( heap[son].val < heap[node].val ) {
      if ( son <= indH ) {
		swap( son, node );
	    node = son;
	  } 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;
  if ( node <= indH ) {
    repairUpp( node );
    repairDown( node );
  }
}


int main() {
  FILE *fin = fopen( "heapuri.in", "r" );
  FILE *fout = fopen( "heapuri.out" , "w" );
  int n, i, type, x, j;
  
  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;
	}
	for ( j = 1; j <= indH; ++j ) {
      printf( "%d ", heap[j].val );
	}
	printf( "\n" );
  }
  fclose( fin );
  fclose( fout );
  return 0;
}