Cod sursa(job #3362367)

Utilizator nicoleta_iancuIancu Nicoleta nicoleta_iancu Data 7 august 2026 16:30:37
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.59 kb

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int NMAX = 200002;
struct heap {
    pair<int, int> elem[NMAX];
    int position[NMAX];//position[i]=pe ce pozitie in heap se alfa elementul inserat al i-lea
    int n;
    int leftSon(int& crt) {
        return 2 * crt;
    }
    int rightSon(int& crt) {
        return 2 * crt + 1;
    }
    int father(int& crt) {
        return crt / 2;
    }
    void goDown(int k) {
        int son = 0;
        do {
            int r = rightSon(k);
            int l = leftSon(k);
            if (l <= n &&  elem[l].first <= elem[k].first && (r>n || elem[l].first<=elem[r].first)) {
                son = l;
                swap(position[elem[k].second], position[elem[l].second]);
                swap(elem[k], elem[l]);
                k = son;
            }
            else if (r <= n && elem[r].first < elem[k].first) {
                son = r;
                swap(position[elem[k].second], position[elem[r].second]);
                swap(elem[k], elem[r]);
                k = son;
            }
            else {
                son = 0;
            }
        } while (son != 0);
    }
    void goUp(int k) {//rearangam sus
        while (father(k) >= 1 && elem[father(k)].first >= elem[k].first) {
            swap(position[elem[k].second], position[elem[father(k)].second]);
            swap(elem[k], elem[father(k)]);
            k = father(k);
        }
    }

    void erase(int k) {
        swap(position[elem[k].second], position[elem[n].second]);
        swap(elem[k], elem[n]);
        n--;
        if ((k > 1) && elem[k] < elem[father(k)]) {//mergem in sus
            goUp(k);
        }
        else {//mergem in jos
            goDown(k);
        }
    }
    void insert(int newVal, int idx) {
        n++;
        elem[n] = make_pair(newVal, idx);
        position[idx] = n;
        goUp(n);
    }

    int getMin() {
        return elem[1].first;
    }
};
int main()
{

    int q;
    fin >> q;
    int op, elem, ord;
    heap h;
    h.n = 0;
    int idx = 1;
    while (q) {
        fin >> op;
        switch (op)
        {
        case 1:
            fin >> elem;
            h.insert(elem, idx);
            ++idx;
            break;
        case 2:

            fin >> ord;
            h.erase(h.position[ord]);
            break;
        default:
            fout << h.getMin() << "\n";
            break;
        }

        --q;
    }
    return 0;
}
//=^..^=