Cod sursa(job #1853037)

Utilizator alexburdescuBurdescu Alexandru alexburdescu Data 21 ianuarie 2017 13:16:08
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include<fstream>
#include<algorithm>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
struct per
{
    int poz,val;
};
per heap[200009];
int nv,n,nh;
char viz[200009];
void urcare(per heap[], int p);
void coborare(per heap[] , int nh , int p);
int main ()
{
    fin>>n;
    nh=0;
    nv=0;
    for(int i=1; i<=n; i++)
    {
        int tip,x;
        fin>>tip;
        if(tip==1)
        {
            fin>>x;
            nv++;
            nh++;
            heap[nh].val=x;
            heap[nh].poz=nv;
            viz[nv]=0;
            urcare( heap , nh);
        }
        if(tip==2)
        {
            fin>>x;
            viz[x]=1;
        }
        if(tip==3)
        {
            while(viz[heap[1].poz]==1)
            {
                swap(heap[1],heap[nh]);
                nh--;
                coborare(heap,nh,1);
            }
            fout<<heap[1].val<<"\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}
void urcare(per heap[], int p)
{
    while(p>=2 && heap[p].val<heap[p/2].val)
    {
        swap(heap[p],heap[p/2]);
        p=p/2;
    }
}
void coborare(per heap[] , int nh , int p)
{
    while(2*p<=nh)
    {
        int r=2*p;
        if(r+1<=nh && heap[r].val>heap[r+1].val)
        {
            r++;
        }
        if(heap[p].val>heap[r].val)
        {
            swap(heap[p],heap[r]);
            p=r;
        }
        else
        {
            break;
        }
    }
}