Cod sursa(job #3163994)

Utilizator iulia_morariuIuli Morariu iulia_morariu Data 1 noiembrie 2023 20:48:31
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

pair<int, int> heap[200005];
int poz[200005];
int siz = 0;
int inde = 0;

void up(int p){
    while(p > 1){
        if(heap[p].first < heap[p / 2].first){
            swap(heap[p], heap[p / 2]);
            swap(poz[ heap[p].second ], poz[ heap[p / 2].second  ]);
            p /= 2;
        }else break;
    }
}

void down(int p){
    while(p * 2  <= siz){
        int c = p * 2;
        if(c + 1 <= siz &&  heap[c].first > heap[c + 1].first){
            c++;
        }

        if(heap[c].first < heap[p].first){
            swap(heap[c], heap[p]);
            swap(poz[ heap[c].second  ], poz[ heap[p].second  ] );
            p = c;
        }else break;
    }
}

void add(int x){
    siz++;
    inde++;
    heap[ siz ].first = x;
    heap[ siz ].second = inde;
    poz[ inde ] = siz;

    up( poz[ inde ] );
}

void elim(int ind){
    int pHeap = poz[ind];
    swap(heap[ pHeap  ], heap[ siz ]);
    swap(poz[ heap[pHeap].second ], poz[ heap[siz].second ] );
    siz--;

    down(pHeap);
    up(pHeap);
}




int main(){
    cin.tie(0);ios::sync_with_stdio(0);

    int n; fin >> n;
    for(int i = 0; i < n; i++){
        int op; fin >> op;
        if(op == 3){
            fout << heap[1].first << "\n";
        }else if(op == 2){
            int p; fin >> p;
            elim(p);
        }else{            int x; fin >> x;
            add(x);
        }
    }


    return 0;
}