Cod sursa(job #1146659)

Utilizator swim406Teudan Adina swim406 Data 19 martie 2014 10:34:16
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <stdio.h>
#define NMAX 200005

using namespace std;

int H[NMAX], pos[NMAX], L, val[NMAX], NR;

void minim() {
    printf ("%d\n", val[H[1]]);
}

void insert() {
    int x, aux;
    scanf ("%d", &x);
    val[++NR] = x;
    pos[NR] = ++L;
    H[L] = NR;
    x = L;
    while (x/2 && val[H[x/2]] > val[H[x]]) {
        aux = H[x/2];
        H[x/2] = H[x];
        H[x] = aux;
        pos[H[x/2]] = x/2;
        pos[H[x]] = x;
        x /= 2;
    }
}

void order() {
    int x, y, aux;
    scanf ("%d", &x);
    val[x] = -1;
    x = pos[x];
    while (x/2 && val[H[x/2]] > val[H[x]]) {
        aux = H[x/2];
        H[x/2] = H[x];
        H[x] = aux;
        pos[H[x/2]] = x/2;
        pos[H[x]] = x;
        x /= 2;
    }
    pos[H[1]] = 0;
    H[1] = H[L];
    pos[H[1]] = 1;
    --L;
    x = 1;
    y = 0;
    if (L > 1)
        while (x != y) {
            y = x;
            if (2*x <= L && val[H[x]] > val[H[2*x]]) x = y*2;
            if (2*x + 1 <= L && val[H[x]] > val[H[2*x+1]]) x = y*2+1;
            aux = H[x];
            H[x] = H[y];
            H[y] = aux;
            pos[H[y]] = y;
            pos[H[x]] = x;
        }

}

int main() {
    freopen ("heapuri.in", "r", stdin);
    freopen ("heapuri.out", "w", stdout);
    int N, opt;
    scanf ("%d", &N);
    while (N--) {
        scanf ("%d", &opt);
        switch (opt) {
            case 1: insert(); break;
            case 2: order(); break;
            case 3: minim(); break;
        }
    }
    return 0;
}