Cod sursa(job #2416430)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 27 aprilie 2019 15:51:44
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>

using namespace std;

vector<int> v, heap, pos;
int n, szheap, szin;

void schimb(int p1, int p2){
    swap(heap[p1], heap[p2]);
    swap(pos[heap[p1]], pos[heap[p2]]);
}

void heapsus(int p){
    if(p == 1)
        return;
    if(v[heap[p]] < v[heap[p / 2]]){
        schimb(p, p / 2);
        heapsus(p / 2);
    }
}

void heapjos(int p){
    int f1 = 2 * p, f2 = 2 * p + 1, np = p;
    if(f1 <= szheap && v[heap[p]] > v[heap[f1]]) np = f1;
    if(f2 <= szheap && v[heap[np]] > v[heap[f2]]) np = f2;
    if(np != p){
        schimb(p, np);
        heapjos(np);
    }
}

void add(int x){
    szin++;
    v.push_back(x);
    heap.push_back(szin);
    szheap++;
    pos.push_back(szheap);
    heapsus(pos[szin]);
}

void del(int x){
    int elim = pos[x];
    schimb(pos[x], szheap);
    szheap--;
    heap.pop_back();
    heapsus(elim);
    heapjos(elim);
}

int main()
{
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    int n;
    fin >> n;
    v.push_back(0);
    heap.push_back(0);
    pos.push_back(0);
    for(int i = 1; i <= n; ++i){
        int op, x;
        fin >> op;
        if(op < 3) fin >> x;
        if(op == 1) add(x);
        else if(op == 2) del(x);
        else fout << v[heap[1]] << "\n";
    }
    return 0;
}