Cod sursa(job #3359040)

Utilizator PortallosAlexandru Vladimir Portallos Data 23 iunie 2026 10:05:58
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
#define NMAX 200001

int heap[NMAX], pozitie[NMAX], ordinea[NMAX];
int n, dim, inserari, c, x;

void swapNodes(int a, int b) {
    pozitie[ordinea[a]] = b;
    pozitie[ordinea[b]] = a;
    swap(heap[a], heap[b]);
    swap(ordinea[a], ordinea[b]);
}

void urcare(int child) {
    while (child > 1 && heap[child] < heap[child / 2]) {
        swapNodes(child, child / 2);
        child /= 2;
    }
}

void coborare(int parinte) {
    int child = 2 * parinte;
    while (child <= dim) {
        if (child < dim && heap[child + 1] < heap[child])
            child++;

        if (heap[child] >= heap[parinte])
            break;

        swapNodes(parinte, child);
        parinte = child;
        child = 2 * parinte;
    }
}

void insereaza(int x) {
    inserari++;
    dim++;
    heap[dim] = x;
    ordinea[dim] = inserari;
    pozitie[inserari] = dim;
    urcare(dim);
}

void elimina(int index) {

    int i = pozitie[index];
    heap[i] = heap[dim];
    ordinea[i] = ordinea[dim];
    pozitie[ordinea[i]] = i;
    dim--;

    if (i > dim)
        return;

    urcare(i);
    coborare(i);
}

int main() {

    fin >> n;
    for (int i = 1; i <= n; i++) {
        fin >> c;
        if (c==1) {
            fin >> x;
            insereaza(x);
        }
        if (c==2) {
            fin >> x;
            elimina(x);
        }
        if (c==3) {
            fout << heap[1] <<endl;
        }
    }

    return 0;
}