Cod sursa(job #2113211)

Utilizator Constantin.Dragancea Constantin Constantin. Data 24 ianuarie 2018 12:53:31
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
using namespace std;

int P[200010],H[200010],A[200010],k,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){
        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(P[H[i]], P[H[son]]);
            swap(H[i], H[son]);
            i = son;
        }
        else son=0;
    }
}

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

void del(int pos){
    swap(H[pos], H[k]);
    swap(P[H[pos]], P[H[k]]);
    k--;
    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;
}