Cod sursa(job #523840)

Utilizator mytzuskyMihai Morcov mytzusky Data 19 ianuarie 2011 15:48:11
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>

#define nmax 200010
using namespace std;


int n,L,nr;
int a[nmax], heap[nmax], poz[nmax];

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

        poz[heap[x]]= x;
        poz[heap[x/2]]=x/2;

        x/=2;
    }
}

void pop(int x)
{
    int y=0;
    while(x!=y){
    y=x;
    if(2*y <= L && a[heap[x]] > a[heap[y*2]])
            x=y*2;
    if(2*y+1 <= L && a[heap[x]] > a[heap[y*2+1]])
            x=y*2+1;

        int aux = heap[x];
        heap[x] = heap[y];
        heap[y] = aux;

        poz[heap[x]]= x;
        poz[heap[y]]= y;
    }
}
int main()
{
    int op, x;
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");

    f>>n;

    for(int i=0;i<n;i++)
    {
        f>>op;

        if(op==1)
        {
            f>>x;

            L++;
            nr++;
            a[nr]=x;
            heap[L]=nr;
            heap[nr]=L;
            push(L);
        }
        else
            if(op==2)
            {
                f>>x;

                a[x]=-1;
                push(poz[x]);
                poz[heap[1]] = 0;
                heap[1] = heap[L--];
                poz[heap[1]] = 1;
                if(L>1) pop(1);
            }
            else
                if(op==3)
                    g<<a[heap[1]]<<"\n";
    }

    return 0;
}