Cod sursa(job #1317766)

Utilizator 0051David Sera 0051 Data 15 ianuarie 2015 09:52:45
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

#define MAX 1000

int heap[MAX],n;
int a[MAX];

void shift(int nod)
{
    int son=0;
    do{
        son=0;
        if(heap[2*nod] <= n)
        {
            son=2*nod;
            if(heap[2*nod + 1] <= n && heap[2*nod+1] < heap[2*nod])
                son=2*nod+1;
            if(heap[son] >= heap[nod])
                son=0;
        }
        if(son)
        {
            swap(heap[son],heap[nod]);
            swap(a[son],a[nod]);
            nod=son;
        }
    }while(son);
}

void perc(int nod)
{
    while(nod>1 && heap[nod/2]>heap[nod])
    {
        swap(heap[nod], heap[nod/2]);
        swap(a[nod], a[nod/2]);
        nod=nod/2;
    }
}

int main()
{
    int m, x = 0;
    fin>>m;
    while(m--)
    {
        int op,nr;
        fin>>op;
        if(op==1)
        {
            fin>>nr;
            heap[++n]=nr;
            a[++x]=n;
            perc(n);
        }
        if(op==2)
        {
            fin>>nr;
            nr=a[nr];
            swap(heap[n],heap[nr]);
            swap(a[n],a[nr]);
            n--;
            perc(nr);
            shift(nr);
        }
        if(op==3)
        {
            cout<<heap[1]<<endl;
        }
    }
    fin.close();
    fout.close();
    return 0;
}