Cod sursa(job #1781817)

Utilizator AlexandruRudiAlexandru Rudi AlexandruRudi Data 17 octombrie 2016 15:05:34
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>

using namespace std;

int h[200005],n,sh,c,x,a[200005],b[200005],t;


void up(int pos){
    if(pos==1) return;
    if(h[pos/2]<=h[pos]) return;
    swap(a[b[pos/2]],a[b[pos]]);
    swap(b[pos/2],b[pos]);
    swap(h[pos/2],h[pos]);
    up(pos/2);
}

void down(int pos){
    if(2*pos>sh) return;
    if(2*pos==sh){
        if(h[pos]<=h[2*pos]) return;
        swap(a[b[pos]],a[b[2*pos]]);
        swap(b[pos],b[2*pos]);
        swap(h[pos],h[2*pos]);
    }
    else{
        if(h[pos]<=h[2*pos] && h[pos]<=h[2*pos+1]) return;
        int fiu;
        if(h[2*pos]<h[2*pos+1]) fiu=2*pos;
        else fiu=2*pos+1;
        swap(a[b[pos]],a[b[fiu]]);
        swap(b[pos],b[fiu]);
        swap(h[pos],h[fiu]);
        down(fiu);
    }
}

void del(int pos){
    h[pos]=-1;
    swap(h[pos],h[sh]);
    swap(a[b[pos]],a[b[sh]]);
    swap(b[pos],b[sh]);
    sh--;
    if(pos==1) down(pos);
    else if (h[pos]>h[pos/2]) down(pos);
    else up(pos);
}

int main()
{
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");
    in >> n;
    for(int i=1;i<=n;i++) h[i]=-1;
    for(int i=1;i<=n;i++){
        in >> c;
        if(c==1){
            in >> x;
            sh++, t++;
            h[sh]=x;
            b[sh]=t;
            a[t]=sh;
            up(sh);
        }
        else if(c==2){
            in >> x;
            del(a[x]);
        }
        else out << h[1] << '\n';
        //for(int i=1;i<=sh;i++) cout << h[i] << ' ';
        //cout << '\n';
    }
}