Cod sursa(job #1594540)

Utilizator grimmerFlorescu Luca grimmer Data 9 februarie 2016 15:58:08
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int n,siz = 0,order[200005];
struct node{
    int val,ind;
};
node h[200005];
void up(int poz){
    int k;
    k = poz/2;
    if(h[k].val > h[poz].val && poz != 0){
        order[h[k].ind] = poz;
        order[h[poz].ind] = k;
        swap(h[k],h[poz]);
        up(k);
    }
}
void down(int poz){
    int lf_son, rg_son;
    if(poz <= siz/2){
        lf_son = 2*poz;
        rg_son = 2*poz+1;
        if(h[poz].val > h[lf_son].val || h[poz].val > h[rg_son].val){
            if(h[lf_son].val >= h[rg_son].val){
                order[h[poz].ind] = rg_son;
                order[h[rg_son].ind] = poz;
                swap(h[poz],h[rg_son]);
                down(rg_son);
            }
            else{
                order[h[poz].ind] = lf_son;
                order[h[lf_son].ind] = poz;
                swap(h[poz],h[lf_son]);
                down(lf_son);
            }
        }
    }
}
int main()
{
    int i,cod,cnt = 0,x,p;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&n);
    for(i=1; i<=n; ++i){
        scanf("%d",&cod);
        if(cod == 1){
            ++cnt;
            scanf("%d",&x);
            h[++siz].val = x;
            h[siz].ind = cnt;
            order[cnt] = cnt;
            h[siz+1].val = 1000000001;
            h[siz+1].ind = 200005;
            up(siz);
        }
        if(cod == 2){
            scanf("%d",&x);
            p = order[x];
            swap(h[p],h[siz]);
            h[siz].val = 1000000001;
            h[siz].ind = 200005;
            --siz;
            down(p);
        }
        if(cod == 3)
            printf("%d\n",h[1].val);
    }
    return 0;
}