Cod sursa(job #3305827)

Utilizator Iustin_Mircea2010Iustin Mircea Iustin_Mircea2010 Data 5 august 2025 16:46:43
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 2e5 + 5;

struct HeapNode{
    int value, index;
};

struct Heap{
    HeapNode arr[nmax];
    int poz[nmax], curr = 0;

    void SwapNodes(int x, int y){
        poz[arr[x].index] = y;
        poz[arr[y].index] = x;
        swap(arr[x], arr[y]);
    }

    void GoUp(int node){
        int a = node / 2, b = node;
        while(a && arr[a].value > arr[b].value){ //am ce sa schimb
            SwapNodes(a, b);
            b = a;
            a /= 2;
        }
    }

    void GoDown(int node){
        while(node * 2 <= curr){ //am ce sa schimb
            int one = arr[node].value;
            int two = arr[2 * node].value;
            int three = 1e9;
            if(node * 2 + 1 <= curr)
                three = arr[2 * node + 1].value;
            if(one <= two && one <= three) return;
            if(two <= three){
                SwapNodes(node, 2 * node);
                node *= 2;
            }
            else{
                SwapNodes(node, 2 * node + 1);
                node = node * 2 + 1;
            }
        }
    }

    void Insertion(int x, int cnt){
        arr[++curr] = {x, cnt};
        poz[cnt] = curr;
        GoUp(curr);
    }

    void Deletion(int cnt){
        int original = poz[cnt];
        SwapNodes(poz[cnt], curr);
        curr--; // deleted
        //now update the moved node, the one that previously was curr
        GoUp(original);
        GoDown(original);
    }

    int Query(){
        return arr[1].value;
    }
}h;


int main()
{
    ifstream cin("heapuri.in");
    ofstream cout("heapuri.out");
    
    int n, cnt = 0;
    cin >> n;
    for(int i = 1; i <= n; i++){
        int t, x;
        cin >> t;
        if(t == 1){
            cin >> x;
            h.Insertion(x, ++cnt);
        }
        else if(t == 2){
            cin >> x;
            h.Deletion(x);
        }
        else{
            cout << h.Query() << '\n';
        }
    }


    return 0;
}