Cod sursa(job #1400254)

Utilizator hasmasandragosHasmasan Dragos hasmasandragos Data 25 martie 2015 10:39:31
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
#define fiu_st(x) 2*x
#define fiu_dr(x) 2*x+1
#define tata(x) x/2
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
const int nmax=200005;
int n,m,t,q,x,p; // n means heapsize , and m means the size of the initial array
int heap[nmax],a[nmax],poz[nmax]; // in heap vom tine indicii din vectorul initial

void schimb (int x,int y)
{
    int aux;
    poz[heap[x]]=y;
    poz[heap[y]]=x;
    aux=heap[x];
    heap[x]=heap[y];
    heap[y]=aux;
}

void sus (int nod)
{
   while (nod>1 && a[heap[tata(nod)]]>a[heap[nod]])
   {
       schimb(nod,tata(nod));
       nod=tata(nod);
   }
}

void jos (int nod)
{
    int ok=1,fiu; // interschimbam cu fiul minim
    while (ok && fiu_st(nod)<=n)
    {
        ok=0;
        fiu=fiu_st(nod);
        if ((fiu_dr(nod)<=n ) && (a[heap[fiu_dr(nod)]]<a[heap[fiu_st(nod)]]))
         fiu=fiu_dr(nod);
        if (a[heap[nod]]>a[heap[fiu]])
        {
            ok=1;
            schimb(nod,fiu);
            nod=fiu;
        }
    }
}

int main()
{
    f>>t;
    while (t--)
    {
        f>>q;
        if (q==1)
        {
           f>>x;
           n++; // crestem heapul
           m++; // creste vectorul
           a[m]=x;
           heap[n]=m;
           poz[m]=n;
           sus(n);
        }
        if (q==2)
        {
            f>>x;
            p=poz[x];
            schimb(p,n);
            n--;
            if ((p > 1) && (a[heap[tata(p)]] > a[heap[p]]))
            {
                sus(p);
            }
            else
            {
                jos(p);
            }
        }
        if (q==3)
         g<<a[heap[1]]<<'\n';
    }
    return 0;
}