Cod sursa(job #2437915)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 10 iulie 2019 18:46:21
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int inf = 1000000005;

int heap[200005], v[200005], v2[200005], poz, n;

void schimb(int nod1, int nod2){
    swap(v2[nod1], v2[nod2]);
    v[v2[nod1]] = nod1;
    v[v2[nod2]] = nod2;
    swap(heap[nod1], heap[nod2]);
}

void inserez(int x){
    poz++;
    n++;
    heap[poz] = x;
    v[n] = poz;
    v2[poz] = n;
    int p = poz;
    while (heap[p] < heap[p / 2] && p > 0){
        schimb(p, p / 2);
        p /= 2;
    }
}

void sterg(int x){
    int nod = v[x];
    schimb(nod, poz);
    heap[poz] = inf;
    poz--;
    int p = nod;
    while (2 * p <= poz){
        if (heap[p] <= heap[2 * p] && heap[p] <= heap[2 * p + 1])
            break;
        if (heap[2 * p] < heap[2 * p + 1]){
            schimb(p, 2 * p);
            p = 2 * p;
        }
        else{
            schimb(p, 2 * p + 1);
            p = 2 * p + 1;
        }
    }
}

int main()
{
    int nr;
    fin >> nr;
    for (int i = 1; i <= nr; i++){
        int cod, x;
        fin >> cod;
        if (cod == 1){
            fin >> x;
            inserez(x);
        }
        else if (cod == 2){
            fin >> x;
            sterg(x);
        }
        else
            fout << heap[1] << '\n';
    }
    return 0;
}