Cod sursa(job #2805686)

Utilizator andrei_marciucMarciuc Andrei andrei_marciuc Data 21 noiembrie 2021 18:37:18
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 kb
#include <stdio.h>
#include<set>
#define MAX 200001

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

template<class TYPE>
class min_heap {
private:
    int *heap;
    int sz;
    const int TOP = 1;
    inline int parent( int idx ) {
        return ( idx >> 1 );
    }

    inline int left( int idx ) {
        return ( idx << 1 );
    }

    inline int right( int idx ) {
        return ( idx << 1 ) + 1;
    }

public:
    min_heap( int size ) {
        heap = new int[ size + 10 ]();
        sz = 0;
    }

    void add( int no ) {
        heap[ ++sz ] = no;
        int poz = sz;
        bool isheap = 0;
        while( poz > 1 && !isheap ) {
            int p = parent( poz );
            if( heap[ poz ] < heap[ p ] ) {
                swap( heap[ p ], heap[ poz ] );
                poz = p;
            } else isheap = 1;
        }
    }

    void remove_top() {
        heap[ 1 ] = heap[ sz-- ];
        int poz = 1;
        bool isheap = 0;
        while( left( poz ) <= sz && !isheap ) {
            int lf = left( poz );
            int rg = right( poz );
            int p = lf;
            if( rg <= sz && heap[ rg ] < heap[ lf ] )
                p = rg;

            if( heap[ poz ] > heap[ p ] ) {
                swap( heap[ p ], heap[ poz ] );
                poz = p;
            } else isheap = 1;
        }
    }

    int top() {
        return heap[ TOP ];
    }

};

min_heap<int> H( MAX );
int timp[ 200001 ], t;
std::set<int> he;

int main()
{
    int q;
    FILE *fin = fopen( "heapuri.in", "r" );
    FILE *fout = fopen( "heapuri.out", "w" );

    fscanf( fin, "%d", &q );

    int type, no;
    while( q-- ) {
        fscanf( fin, "%d", &type );
        
        if( type == 1 ) {
            fscanf( fin, "%d", &no );
          //  H.add( no );
            he.insert( no );
            timp[ t++ ] = no;
        } else if( type == 2 ) {
            fscanf( fin, "%d", &no );
            he.erase( timp[ no - 1 ] );
        } else {
            fprintf( fout, "%d\n", *( he.begin() ) );
        }
    }

    fclose( fin );
    fclose( fout );
    return 0;
}