Cod sursa(job #2381738)

Utilizator Anakin1001George Giorgiu Gica Anakin1001 Data 17 martie 2019 12:52:10
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int i,n,v[200001],k,a,x,h[200001],p[200001],nr;
void down_heap(int poz,int n){
    while(poz*2<=n){
        int st=poz*2;
        if(st+1<=n&&v[h[st+1]]<v[h[st]])
            st=st+1;
        if(v[h[poz]]>v[h[st]]){
            swap(p[h[poz]],p[h[st]]);
            swap(h[poz],h[st]);
            poz=st;
        }
        else
            return;
    }
}
void up_heap(int poz){
    while(poz/2>=1){
        int st=poz/2;
        if(v[h[poz]]<v[h[st]]){
            swap(p[h[poz]],p[h[st]]);
            swap(h[poz],h[st]);
            poz=st;
        }
        else
            return;
    }
}
int main()
{   f>>n;
    nr=0;
    for(i=1;i<=n;i++){
        f>>a;
        if(a==3)
            g<<v[h[1]]<<'\n';
        else{
            if(a==1){
                f>>x;
                v[++nr]=x;
                h[++k]=nr;
                p[nr]=k;
                up_heap(k);
            }
            else{
                f>>x;
                int pos=p[x];
                swap(p[x],p[h[k]]);
                swap(h[k],h[pos]);
                k--;
                if(pos/2>=1&&v[pos]<v[pos/2])
                    up_heap(pos);
                else
                    down_heap(pos,k);
            }
        }
    }
    return 0;
}