Cod sursa(job #2617014)

Utilizator CryshanaGanea Carina Cryshana Data 20 mai 2020 16:32:52
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define MAX_INT 200003
vector<int> H;
vector<int> V;
int P[MAX_INT];

void push( int i ){
    while( i/2 && V[H[i/2]] > V[H[i]]){
        swap(H[i/2], H[i]);
        P[H[i/2]] = i/2;
        P[H[i]] = i;
        i = i/2;
    }
}

void pop( int i ){
    if( i*2 >= H.size()){
        P[H[i]] = -1;
        H[i] = H[H.size()-1];
        P[H[i]] = i;
        H.pop_back();
    }
    else{
        P[H[i]] = -1;
        H[i] = H[H.size()-1];
        P[H[i]] = i;
        H.pop_back();
        while( i * 2 < H.size() ){
            int j = i;
            if( V[H[i]] > V[H[i*2]])
                j = i * 2;
            if ( i * 2 + 1 < H.size() ){
                if( V[H[j]] > V[H[i*2 + 1]])
                    j = i*2 + 1;
            }
            if( i != j){
                swap(H[i], H[j]);
                P[H[i]] = i;
                P[H[j]] = j;
                i = j;
            } else break;
        }
    }
}

int main() {
    ifstream in ("heapuri.in");
    ofstream out ("heapuri.out");
    int n;
    in >> n;
    H.push_back(0);
    V.push_back(0);
    while(n){
        n--;
        int op, x;
        in >> op;
        switch (op){
        case 1:
            {
                in >> x;
                V.push_back(x);
                H.push_back(V.size()-1);
                P[V.size()-1] = H.size()-1;
                push(H.size()-1);
                break;
            }
        case 2:
            {
                in >> x;
                V[x] = -1;
                pop(P[x]);
                break;
            }
        default:
            {
                out << V[H[1]] << "\n";
            }
        }
    }
    return 0;
}