Cod sursa(job #2137233)

Utilizator sulzandreiandrei sulzandrei Data 20 februarie 2018 17:59:22
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>
#include <set>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
#define SIZE 200000+10
int Heap[SIZE],
pozHx[SIZE], // pozHx[nr] the nr-th number inserted is located on pozHx[nr] in Heap
heapToElpoz[SIZE];//  heapToElpoz[i] , on pozition i in heap, Heap[i] is the heapToElpoz[i]'th element inserted
int ls(int n){return 2*n;};
int rs(int n){return 2*n+1;};
int pr(int n){return n/2;};
int heapsize = 0;
void doswap(int pos, int othpos)
{
     // pozition in heap of x
    swap(pozHx[heapToElpoz[pos]], pozHx[heapToElpoz[othpos]]);
    // x
    swap(heapToElpoz[pos],heapToElpoz[othpos]);
    // el
    swap(Heap[pos],Heap[othpos]);
}
void pushH(int el, int x,int &n)
{
    n++;
    Heap[n] = el;
    pozHx[x] = n;
    heapToElpoz[n] = x;
    int pos = n;
    while(true)
    {
        if(pos == 1)
            break;
        if(Heap[pos] < Heap[pr(pos)])
        {
            doswap(pos,pr(pos));
            pos = pr(pos);
        }
        else
        {
            break;
        }
    }
}
void removeH(int x, int& n)
{

    int pos = pozHx[x], othpos = n;
    doswap(pos,othpos);
    n--;
    while(pos <= n)
    {
        othpos = pos;
        if(pos > n)
            break;
        if( ls(pos) <= n && Heap[ls(pos)] < Heap[pos])
            othpos = ls(pos);
        if( rs(pos)<= n && Heap[rs(pos)] < Heap[othpos])
            othpos = rs(pos);
        if(pos == othpos)
            break;
        else
        {
            doswap(pos,othpos);
            pos = othpos;
        }
    }
}
int main()
{
    int op,x,n;
    in >> n;
    int indexinsert=0;
    for(int i = 0 ; i < n ; i++)
    {
        in >> op;
        switch(op)
        {
            case 1:
                in >> x;
                indexinsert++;
                pushH(x,indexinsert,heapsize);
                break;
            case 2:
                in >> x;
                removeH(x,heapsize);
                 break;
            case 3:
                out<<Heap[1]<<'\n';
                break;
        }
    }

	return 0;
}