Cod sursa(job #2117608)

Utilizator Constantin.Dragancea Constantin Constantin. Data 28 ianuarie 2018 23:36:02
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
using namespace std;

int P[200010],H[200010],A[200010],k,h,n,c,x;

void heapup(int i){
    int key = H[i];
    while (i>1 && A[key] < A[H[i/2]]){
        P[H[i/2]] = i;
        H[i] = H[i/2];
        i/=2;
    }
    H[i] = key;
    P[key] = i;
}

void heapdown(int i){
    int son = i;
    while (son){
        son = i;
        if (2*i <= k && A[H[i]] > A[H[2*i]]) son = 2*i;
        if (2*i + 1 <= k && A[H[son]] > A[H[2*i + 1]]) son = 2*i + 1;
        if (son != i){
            swap(H[i], H[son]);
            P[H[son]] = son;
            P[H[i]] = i;
            i = son;
        }
        else son=0;
    }
}

void add(){
    H[++h] = k;
    P[k] = h;
    heapup(h);
}

void del(int pos){
    H[pos] = H[h];
    P[H[h]] = pos;
    h--;
    heapdown(pos);
}

int main(){
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    ifstream cin ("heapuri.in");
    ofstream cout ("heapuri.out");
    cin >> n;
    while (n--){
        cin >> c;
        if (c == 3) cout << A[H[1]] << "\n";
        else{
            cin >> x;
            if (c == 1) A[++k] = x, add();
            if (c == 2) del(P[x]);
        }
    }
    return 0;
}