Cod sursa(job #1853033)

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