Cod sursa(job #523199)

Utilizator andu04Popa Andi andu04 Data 17 ianuarie 2011 13:35:47
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <stdio.h>
#define NMAX 200001
using namespace std;

int A[NMAX],H[NMAX],P[NMAX],n,c,nr,l;


void push(int x)
{
    while (x>1 && A[H[x]]<A[H[x/2]])
    {
        int aux=H[x];
        H[x]=H[x/2];
        H[x/2]=aux;

        P[H[x/2]]=x/2;
        P[H[x]]=x;
        x/=2;
    }
}
void pop(int x)
{
    while ((2*x<=l || 2*x+1<=l) && (A[H[x]]>A[H[2*x]] || A[H[x]]>A[H[2*x+1]]))
    {
        if (A[H[x]]>A[H[2*x]])
        {
            int aux=H[x];
            H[x]=H[2*x];
            H[2*x]=aux;
            P[H[x]]=x;
            P[H[2*x]]=2*x;
        }
        else
            if (A[H[x]]>A[H[2*x+1]])
            {
                int aux=H[x];
                H[x]=H[2*x+1];
                H[2*x+1]=aux;
                P[H[x]]=x;
                P[H[2*x+1]]=2*x+1;
            }
    }




}
void citire()
{
    freopen ("heapuri.in","r",stdin);
    freopen ("heapuri.out","w",stdout);
    scanf ("%d",&n);
    int x;
    for (int i=1;i<=n;i++)
    {
        scanf ("%d",&c);
        if (c==3)
            printf("%d\n",A[H[1]]);
        else
        {
            if (c==1)
            {
                scanf ("%d",&x);
                l++;
                A[++nr]=x;
                H[l]=nr;
                P[nr]=l;
                push(l);
            }
            else
            {
                scanf ("%d",&x);
                H[P[x]]=H[l];
                P[H[l]]=P[x];
                P[x]=-1;
                l--;
                if (A[H[x]]<A[H[x/2]])
                    push(P[x]);
                else
                    pop(1);

            }
        }
    }
}

int main()
{
    citire();
    return 0;
}