Cod sursa(job #2022441)

Utilizator dragos231456Neghina Dragos dragos231456 Data 16 septembrie 2017 16:00:00
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <fstream>
#define nmax 200005
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int heap[nmax],v[nmax],p[nmax],t,hlen,op,n,x,pz,mn;
bool ok;
void up(int poz)
{
    ok=1;
    while(ok)
    {
        ok=0;
        if(v[heap[poz]]<v[heap[poz/2]])
        {
            ok=1;
            swap(heap[poz],heap[poz/2]);
            p[heap[poz]]=poz;
            p[heap[poz/2]]=poz/2;
            poz/=2;
        }
    }
}

void down()
{
    int poz=1; ok=1;
    while(ok)
    {
        ok=0; mn=(1<<30);
        if(poz*2<=hlen && v[heap[poz*2]]<v[heap[poz]]) mn=v[heap[poz*2]], pz=poz*2;
        if(poz*2+1<=hlen && v[heap[poz*2+1]]<v[heap[poz]]) mn=v[heap[poz*2+1]],pz=poz*2+1;
        if(mn<=v[heap[poz]])
        {
            swap(heap[poz],heap[pz]);
            p[heap[pz]]=pz;
            p[heap[poz]]=poz;
            poz=pz; ok=1;
        }
    }
}

void afisare()
{
    int k=0;
    for(int i=1;i<=3;++i)
    {
        for(int j=1;j<=(1<<(i-1));++j)
        {
            ++k;
            cout<<heap[k]<<' ';
        }
        cout<<endl;
    }
}

int main()
{
    f>>n;
    for(int i=1;i<=n;++i)
    {
        f>>op;
        if(op==1)
        {
            f>>x;
            ++t; ++hlen;
            v[t]=x;
            heap[hlen]=t;
            up(t);
        }
        else if(op==2)
        {
            f>>pz;
            v[pz]=-1;
            up(p[pz]);
            heap[1]=heap[hlen]; --hlen;
            down();
        }
        else g<<v[heap[1]]<<'\n';
        //afisare();
    }
    return 0;
}