Cod sursa(job #1418762)

Utilizator sulzandreiandrei sulzandrei Data 13 aprilie 2015 22:15:43
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#define rest 200002
ifstream in("heapuri.in");
ofstream out("heapuri.out");
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 H[],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)] )
    {
        swap(P[Ent[pos]],P[Ent[father(pos)]]);
        swap(Ent[pos],Ent[father(pos)]);
        swap(H[pos],H[father(pos)]);
        pos = father(pos);
    }
}
void deleteHeap(int H[],int &n,int x)
{
    int pos = P[x],posmin;
    swap(P[x],P[Ent[n]]);
    swap(Ent[pos],Ent[n]);
    swap(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
        {
            swap(P[Ent[pos]],P[Ent[posmin]]);
            swap(Ent[pos],Ent[posmin]);
            swap(H[pos],H[posmin]);
            pos = posmin;
        }
    }while(1);
}
int main()
{
    int Heap1[rest];
    int NrEle,nthele,n,i,op,x;
    nthele = n = 0;
    in >> NrEle;
    for( i = 1 ; i <= NrEle ; i++)
    {
        in >> op;
        switch(op)
        {
            case 1 : in >> x; ++nthele; insertHeap(Heap1,x,n,nthele); break;
            case 2 : in >> x; deleteHeap(Heap1,n,x); break;
            case 3 : out<<Heap1[1]<<"\n"; break;
        }
    }
    return 0;
}