Cod sursa(job #2616990)

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

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

void pop( int i ){
    if( i*2 + 1 >= H.size()){
        H[i] = H[H.size()-1];
        P[H[i]] = i;
        H.pop_back();
        }
    else{
        H[i] = H[H.size()-1];
        P[H[i]] = i;
        H.pop_back();
        while( i * 2 + 1 < H.size() ){
            int j = i;
            if( V[H[i]] > V[H[i*2 + 1]])
                j = i * 2 + 1;
            if ( i * 2 + 2 < H.size() ){
                if( V[H[j]] > V[H[i*2+2]])
                    j = i*2 + 2;
            }
            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;
    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;
                x--;
                pop(P[x]);
                break;
            }
        default:
            {
                out << V[H[0]] << "\n";
            }
        }
    }
    return 0;
}