Cod sursa(job #2618614)

Utilizator RNedelcuNedelcu Radu RNedelcu Data 25 mai 2020 16:18:48
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
// 1- Insereaza X
// 2 - Sterge al X-lea element intrat in multime
// 3 - Afisare minim

class Heap  // Min Heap
{
private:
    pair<int,int> heap[200001];
    int dim=0;
    void down(int i)
    {
        int smallest = i;
        if( 2*i <= dim && heap[smallest].first>heap[2*i].first)
            smallest = 2*i;
        if(2*i+1 <= dim && heap[smallest].first> heap[2*i+1].first)
            smallest = 2*i+1;
        if(smallest!=i)
        {
            swap(heap[smallest],heap[i]);
            down(smallest);
        }
    }
    void up(int i)
    {
        pair<int,int> key = heap[i];
        while(i>1 && heap[i/2].first>key.first)
        {
            heap[i] = heap[i/2];
            i=i/2;
        }
        heap[i]=key;
    }
public:
    void add(int x)
    {
        heap[++dim]= {x,dim};
        up(dim);
    }
    void erase_ord(int ord)
    {
        ord-=1;
        for(auto i=1; i<=dim; i++)
            if(heap[i].second == ord)
            {
                swap(heap[i],heap[dim]);
                dim--;
                down(i);
            }
    }
    int const get_min() const
    {
        return heap[1].first;
    }
    void afis()
    {
        cout<<"Start afisare\n";
        for(int i=1; i<=dim; i++)
            cout<<heap[i].first<<" "<<heap[i].second<<'\n';
        cout<<"End afisare\n";
    }
};
int main()
{
    Heap heap;
    int N,x,y;
    in>>N;
    while(N--)
    {
        //heap.afis();
        in>>x;
        if(x==1)
        {
            in>>y;
            heap.add(y);
        }
        else if(x==2)
        {
            in>>y;
            heap.erase_ord(y);
        }
        else
            out<<heap.get_min()<<'\n';

    }
    return 0;
}