Cod sursa(job #1721370)

Utilizator oldatlantianSerban Cercelescu oldatlantian Data 25 iunie 2016 14:42:10
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 200005;

int buff, n,
    h[NMAX],
    p[NMAX],
    v[NMAX];

void rise(int k) {
    while(k>1) {
        if(v[h[k/2]]>v[h[k]]) {
            swap(h[k], h[k/2]);
            p[h[k]]   = k;
            p[h[k/2]] = k/2;
            k         = k/2;
        }
        else {
            k = 1;
        }
    }
}

void fall(int k) {
    while(k<=n) {
        if(2*k+1<=n && v[h[2*k+1]]<=v[h[2*k]] && v[h[2*k+1]]<v[h[k]]) {
            swap(h[k], h[2*k+1]);
            p[h[k]]     =   k;
            p[h[2*k+1]] = 2*k+1;
            k = k*2+1;
        }
        else if(2*k<=n && (v[h[2*k]]<=v[2*k+1] || 2*k+1) && v[h[2*k]]<v[h[k]]) {
            swap(h[k], h[2*k]);
            p[h[k]]     =   k;
            p[h[2*k]]   = 2*k;
            k = k*2;
        }
        else {
            k = n+1;
        }
    }
}

void insert(int arg) {
    v[++buff] = arg;
    p[buff]   = ++n;
    h[n]      = buff;

    rise(n);
}

void remove(int arg) {
    swap(h[p[arg]], h[n--]);
    if(h[p[arg]]<h[p[arg]/2])
        rise(p[arg]);
    else
        fall(p[arg]);
}

int main(void) {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int n, tsk, arg;

    scanf("%d",&n);
    while(n--) {
        scanf("%d",&tsk);
        switch(tsk) {
        case 1:
            scanf("%d",&arg);
            insert(arg);
            break;
        case 2:
            scanf("%d",&arg);
            remove(arg);
            break;
        case 3:
            printf("%d\n",v[h[1]]);
            break;
        }
    }

    fclose(stdin);
    fclose(stdout);
    return 0;
}