Cod sursa(job #1419124)

Utilizator sulzandreiandrei sulzandrei Data 14 aprilie 2015 18:59:58
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
#define bswap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
using namespace std;
#define rest 200002
ifstream in("heapuri.in");
ofstream out("heapuri.out");
  int H[rest];
inline int leftson(int i)
{
    return (2*i);
}
inline int rightson(int i)
{
    return(2*i+1);
}
inline int father(int i)
{
    return(i/2);
}
int P[rest],Ent[rest];
void insertHeap(int x,int &n,int nth)
{
    H[++n] = x;
    P[nth] = n;
    Ent[n] = nth;
    int pos = n;
    while( pos>1 && H[pos]<H[father(pos)] )
    {
        bswap(P[Ent[pos]],P[Ent[father(pos)]]);
        bswap(Ent[pos],Ent[father(pos)]);
        bswap(H[pos],H[father(pos)]);
        pos = father(pos);
    }
}
void deleteHeap(int &n,int x)
{
    int pos = P[x],posmin;
    bswap(P[x],P[Ent[n]]);
    bswap(Ent[pos],Ent[n]);
    bswap(H[pos],H[n]);
    n--;
    do
    {
        posmin = pos;
        if( leftson(pos)<=n && H[leftson(pos)]<H[posmin])
            posmin = leftson(pos);
        if( rightson(pos)<=n && H[rightson(pos)]<H[posmin])
            posmin = rightson(pos);
        if(posmin == pos)
           break;
        else
        {
            bswap(P[Ent[pos]],P[Ent[posmin]]);
            bswap(Ent[pos],Ent[posmin]);
            bswap(H[pos],H[posmin]);
            pos = posmin;
        }
    }while(1);
}
int main()
{
    int NrEle,cne,n,op,x;
    cne = n = 0;
    in >> NrEle;
    do
    {
        in >> op;
        switch(op)
        {
            case 1 : in >> x; ++cne; insertHeap(x,n,cne); break;
            case 2 : in >> x; deleteHeap(n,x); break;
            case 3 : out<<H[1]<<"\n"; break;
        }
    }while(--NrEle);
    return 0;
}