Cod sursa(job #2745629)

Utilizator RobertLitaLita Robert RobertLita Data 26 aprilie 2021 20:54:03
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.43 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
class heap
{
private:
    int heap_size;
    static int intrate_heap;
    struct nod
    {
        int val;
        int nr_ordine;
    };
    vector <nod> H;
public:

    heap():heap_size(0) {}
    inline int pozitie_fiu_st(const int p)
    {
        return 2*p+1;
    }
    inline int pozitie_fiu_dr(const int p)
    {
        return 2*p+2;
    }
    inline int pozitie_tata(const int p)
    {
        return (p-1)/2;
    }
    void urca(const int p)
    {
        while(p)
        {
            int tata=pozitie_tata(p);
            if(H[p].val<H[tata].val)
            {
                swap(H[p],H[tata]);
                tata=p;
            }
            else break;
        }
    }
    void push(const int x)
    {
        nod N;
        N.val=x;
        N.nr_ordine=++intrate_heap;
        H.push_back(N);
        heap_size++;
        urca(heap_size-1);
    }
    void coboara(const int p)
    {
        int k=p,j;
        do
        {
            j=k;
            int p_fiu_st=pozitie_fiu_st(j);
            int p_fiu_dr=pozitie_fiu_dr(j);
            if(p_fiu_st<=heap_size && H[p_fiu_st].val<H[k].val)k=p_fiu_st;
            if(p_fiu_st<heap_size && H[p_fiu_dr].val<H[k].val)k=p_fiu_dr;
            swap(H[j],H[k]);
        }
        while(j!=k);
    }
    void pop()
    {
        H[0]=H[heap_size-1];
        H.pop_back();
        heap_size--;
        coboara(0);
    }
    inline int top()
    {
        if(heap_size==0)return -1;
        return H[0].val;
    }
    void pop_intrat(const int p)
    {
        int x=-1,i=0;
        while(x==-1 && i<heap_size)
        {
            if(H[i].nr_ordine==p)x=i;
            i++;
        }
        if(x!=-1)
        {
            H[x]=H[heap_size-1];
            H.pop_back();
            heap_size--;
            coboara(x);
        }
    }
};
int heap::intrate_heap;
int main()
{
    heap heap;
    int n,x;
    f>>n;
    for(int i=1;i<=n;i++)
    {
        char op;
        f>>op;
        if(op=='1')
        {
            f>>x;
            heap.push(x);
        }
        else if(op=='2')
        {
            f>>x;
            heap.pop_intrat(x);
        }
        else
        {
            g<<heap.top()<<'\n';
        }
    }
    return 0;
}