Cod sursa(job #2789400)

Utilizator florinrafiliuRafiliu Florin florinrafiliu Data 27 octombrie 2021 15:06:03
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int maxN = 2e5 + 5;

struct arbore { /// heap ul
    int ind, val;
}heap[maxN];

int poz[maxN]; // pozitia nodurilor in heap in ordinea citirii

void promovare (int node) {
    if(node != 1 && heap[node].val < heap[node/2].val) {
        //actualizez pozitia fiecaruia in heap
        poz[heap[node].ind] = node / 2;
        poz[heap[node/2].ind] = node;
        //interschimb valorile si continui cu promovarea
        swap(heap[node], heap[node/2]);
        promovare(node/2);
    }
}

void cernere (int node, int n) {
    while(2*node <= n) { // avem fiu stang
        int p = 2*node;
        if(p+1 <= n && heap[p].val > heap[p+1].val) // avem fiu drept si acesta este mai bun
            p += 1;

        if(heap[node].val < heap[p].val) return ; // nu trebuie modificat nimic
        // actualizez poz...
        poz[heap[node].ind] = p;
        poz[heap[p].ind] = node;

        swap(heap[node], heap[p]);
        node = p; // continui cernerea
    }
}

void stergere (int node, int &length) {
    swap(heap[node], heap[length]);
    // pun ultimul element pe elemntul ce trebuie sters
    poz[heap[node].ind] = node;
    length -= 1;

    if(node != 1 && heap[node].val < heap[node/2].val)
        promovare(node);
    else
        cernere(node, length);
}

int main() {

    int n; fin >> n;

    int length = 0;
    for(int i = 1; i <= n; ++i) {
        int op; fin >> op;
        if(op == 1) {
            int x; fin >> x;

            heap[++length].val = x;
            heap[length].ind = i; poz[i] = length;

            promovare(length);
        } else if(op == 2) {
            int x; fin >> x;
            stergere(poz[x], length);
        } else {
            fout << heap[1].val << "\n";
        }
    }

    return 0;
}