Cod sursa(job #1524922)

Utilizator andreiudilaUdila Andrei andreiudila Data 14 noiembrie 2015 15:55:21
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

typedef struct { int val, idx; } heap_type;

int v[200001],i,n,op, x,aux,heap_size,index,c1;
heap_type heap[200001];

void up(int x)
{

    while(x>1 && heap[x/2].val>heap[x].val)
    {
        swap(v[heap[x].idx],v[heap[x/2].idx]);
        swap(heap[x/2], heap[x]);

        x/=2;
    }

}

void down(int x)
{
    aux=x;

    while(aux*2<=heap_size){

    index=aux;
    if( heap[2*aux].val < heap[aux].val ) index=2*aux;

    if(2*aux+1 <= heap_size && heap[2*aux+1].val < heap[index].val ) index=2*aux+1;

    if(index==aux) break;

    swap(v[heap[aux].idx],v[heap[index].idx]);
    swap(heap[aux], heap[index]);

    aux=index;

    }

}
int main()
{

    fin>>n;

    for(i=1;i<=n;i++)
    {
        fin>>op;

        if(op==1) {
            fin>>x;
            c1++;

            heap[++heap_size].val=x;
            heap[heap_size].idx=c1;

            v[c1]=heap_size;

            up(heap_size);

            }
        else if (op==2)
        {
            fin>>x;

            v[heap[heap_size].idx]=v[x];
            heap[v[x]]=heap[heap_size];
            --heap_size;

            if (v[x]>1 && heap[v[x]].val<heap[v[x]/2].val) up(v[x]);
            else down(v[x]);

        }
        else fout<<heap[1].val<<"\n";
    }


    return 0;
}