Cod sursa(job #1183490)

Utilizator hrazvanHarsan Razvan hrazvan Data 9 mai 2014 14:02:25
Problema Heapuri Scor 10
Compilator c Status done
Runda Arhiva educationala Marime 2.78 kb
#include <stdio.h>
#define N_MAX 200000
int heap[ N_MAX ], point[ N_MAX ], point2[ N_MAX ], ind = 0;

void urc ( int x ){
    if ( x == 0 )   return ;
    if ( heap[ x ] < heap[ ( x - 1 ) / 2 ] ){
        int aux;
        aux = heap[ x ];  heap[ x ] = heap[ ( x - 1 ) / 2 ];  heap[ ( x - 1 ) / 2 ] = aux;
        aux = point[ point2[ x ] ];  point[ point2[ x ] ] = point[ point2[ ( x - 1 ) / 2 ] ]; point[ point2[ ( x - 1 ) / 2 ] ] = aux;
        aux = point2[ x ];  point2[ x ] = point2[ ( x - 1 ) / 2 ]; point2[ ( x - 1 ) / 2 ] = aux;
        urc ( ( x - 1 ) / 2 );
    }
    return ;
}

void cobor ( int x ){
    if ( x == ind - 1 ) return ;
    int aux, a = 2 * x + 1, b = 2 * x + 2;
    if ( b < ind ){
        if ( heap[ b ] < heap[ a ] && heap[ b ] < heap[ x ] ){
            aux = heap[ x ];  heap[ x ] = heap[ b ];  heap[ b ] = aux;
            aux = point[ point2[ x ] ];  point[ point2[ x ] ] = point[ point2[ b ] ]; point[ point2[ b ] ] = aux;
            aux = point2[ x ];  point2[ x ] = point2[ b ]; point2[ b ] = aux;
            cobor ( b );
        }
        else  if ( heap[ a ] < heap[ x ] ){
            aux = heap[ x ];  heap[ x ] = heap[ a ];  heap[ a ] = aux;
            aux = point[ point2[ x ] ];  point[ point2[ x ] ] = point[ point2[ a ] ]; point[ point2[ a ] ] = aux;
            aux = point2[ x ];  point2[ x ] = point2[ a ]; point2[a ] = aux;
            cobor ( a );
        }
    }
    else if ( a < ind ) if ( heap[ x ] > heap[ a ] ){
        aux = heap[ x ];  heap[ x ] = heap[ a ];  heap[ a ] = aux;
        aux = point[ point2[ x ] ];  point[ point2[ x ] ] = point[ point2[ a ] ]; point[ point2[ a ] ] = aux;
        aux = point2[ x ];  point2[ x ] = point2[ a ]; point2[ a ] = aux;
        cobor ( a );
    }
    return ;
}

int main()
{
    FILE *in = fopen ( "heapuri.in", "r" );
    FILE *out = fopen ( "heapuri.out", "w" );
    int n;
    fscanf ( in, "%d", &n );
    int i, tip, x, aux, aux2;
    for ( i = 0; i < n; i++ ){
        fscanf ( in, "%d", &tip );
        if ( tip == 1 ){
            fscanf ( in, "%d", &x );
            heap[ ind ] = x;
            point[ ind ] = ind;
            point2[ ind ] = ind;
            urc ( ind );
            ind++;
        }
        else  if ( tip == 2 ){
            fscanf ( in, "%d", &x );
            x--;
            aux = heap[ point[ x ] ]; heap[ point[ x ] ] = heap[ ind - 1 ];  heap[ ind - 1 ] = aux;
            aux = point [ x ];  point[ x ] = ind - 1;  point[ point2[ ind - 1 ] ] = aux;
            aux2 = point2[ aux ]; point2[ aux ] = point2[ ind - 1 ];  point2[ ind - 1 ] = aux2;
            ind--;
            if ( aux < ind )  cobor ( aux );
        }
        else    fprintf ( out, "%d\n", heap[ 0 ] );
    }
    fclose ( in );
    fclose ( out );
    return 0;
}