Cod sursa(job #2616936)

Utilizator MihaelaCismaruMihaela Cismaru MihaelaCismaru Data 20 mai 2020 13:18:06
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include<fstream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int marime,numar;
pair<int,int>heap[200001];
int numar_teste,i,test,valoare,locatie[200001];

void urca( int pozitie ){

    while( pozitie > 1 && heap[pozitie].first < heap[pozitie/2].first ){

        swap( locatie[ heap[pozitie/2].second ], locatie[ heap[pozitie].second ] );
        swap( heap[pozitie/2], heap[pozitie] );

        pozitie /= 2;

    }

    return;
}
void coboara( int pozitie ){

    while( pozitie*2 <= marime ){

        int auxiliar=pozitie*2;

        if( auxiliar < marime && heap[auxiliar+1].first < heap[auxiliar].first ){
            auxiliar ++;
        }

        if( heap[pozitie].first > heap[auxiliar].first ){

            swap( locatie[ heap[auxiliar].second ], locatie[ heap[pozitie].second ] );
            swap( heap[auxiliar], heap[pozitie] );

            pozitie = auxiliar;

        }
        else{
            break;
        }
    }

    return;

}
void adauga( int val ){

    heap[++marime] = make_pair( valoare, ++ numar );

    locatie [ numar ] = marime;

    urca( marime );
    coboara( marime );

    return;

}
void elimina( int pozitie ){

    swap( locatie [ heap[pozitie].second ], locatie [ heap[marime].second ] );
    swap( heap[pozitie], heap[marime] );

    marime--;

    urca( pozitie );
    coboara( pozitie );

    return;

}
int main(){
    in >> numar_teste;
    for( i = 1; i <= numar_teste; i ++ ){
        in >> test;
        if( test == 1 ){
            in >> valoare;
            adauga( valoare );
        }
        if( test == 2 ){
            in >> valoare;
            elimina( locatie[valoare] );
        }
        if( test == 3 ){
            out<<heap[1].first<<"\n";
        }
    }
    return 0;
}