Cod sursa(job #2805718)

Utilizator andrei_marciucMarciuc Andrei andrei_marciuc Data 21 noiembrie 2021 19:47:25
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
    
#include <stdio.h>

void swap( int &a, int &b ) {
    a ^= b;
    b ^= a;
    a ^= b;
}

#define MAX 200001
 
int heap[ ( MAX << 1 ) ];

int v[ MAX ];
int poz[ MAX ];
int n, poz_v;

void swap2_punct_0( int i, int j ) {
    swap( heap[ i ], heap[ j ] );
    poz[ heap[ i ] ] = i;
    poz[ heap[ j ] ] = j;
}
 
void merg_jos( int i ) {
    int left = i << 1;
    int right = ( i << 1 ) + 1;
    int maxx = i;
 
    if( left <= n && v[ heap[ left ] ] < v[ heap[ maxx ] ] )
        maxx = left;
    if( right <= n && v[ heap[ right ] ] < v[ heap[ maxx ] ] )
        maxx = right;
 
    if( maxx != i ) {
        swap2_punct_0( i, maxx );
        merg_jos( maxx );
    }
}

void merg_sus( int i ) {
    while( i > 1 && v[ heap[ i ] ] < v[ heap[ i >> 1 ] ] ) {
        swap2_punct_0( i, i >> 1 );
        i >>= 1;
    }
}
 
void esec( int i ) {
    if( i == n )
        n--;
    else {
        heap[ i ] = heap[ n-- ];
        poz[ heap[ i ] ] = i;
        merg_sus( i );
        merg_jos( i );
    }
}
 
int main()
{
    int q, type, no;
    FILE *fin = fopen( "heapuri.in", "r" );
    FILE *fout = fopen( "heapuri.out", "w" );
 
    fscanf( fin, "%d", &q );
    while( q-- ) {
        fscanf( fin, "%d", &type );
        if( type == 1 ) {
            fscanf( fin, "%d", &no );
            v[ ++poz_v ] = no;
            heap[ ++n ] = poz_v;
            poz[ poz_v ] = n;
            merg_sus( n );
        } else if( type == 2 ) {
            fscanf( fin, "%d", &no );
            esec( poz[ no ] );
        } else fprintf( fout, "%d\n", v[ heap[ 1 ] ] );
    }
 
    fclose( fin );
    fclose( fout );
    return 0;
}