Cod sursa(job #2009969)

Utilizator basilescubasil basilescu basilescu Data 11 august 2017 13:23:36
Problema Heapuri Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <cstdio>

using namespace std;

const int N_max = 200000 + 1; // indexam de la unu

int heap[N_max], store[N_max], inv_heap[N_max], N;
int current_heap_size = 0, current_store_size = 0;

void swap(int p1, int p2) {
    int aux = heap[p1];
    heap[p1] = heap[p2];
    heap[p2] = aux;

    aux = inv_heap[heap[p1]];
    inv_heap[heap[p1]] = inv_heap[heap[p2]];
    inv_heap[heap[p2]] = aux;
}

void urca(int p) {
    while(p != 1 && store[heap[p / 2]] > store[heap[p]]) {
        swap(p / 2, p);

        p /= 2;
    }
}

void coboara(int p) {
    int destinatie = p;

    if(2 * p <= current_heap_size && store[heap[2 * p]] < store[heap[p]])
        destinatie = 2 * p;

    if(2*p + 1 <= current_heap_size && store[heap[2*p + 1]] < store[heap[destinatie]])
        destinatie = 2*p + 1;

    if(destinatie != p) {
        swap(destinatie, p);

        coboara(destinatie);
    }
}

void insert_in_heap(int val) {
    store[++current_store_size] = val;
    heap[++current_heap_size] = current_store_size;
    inv_heap[current_store_size] = current_heap_size;

    urca(current_heap_size);
}

void delete_from_heap(int x) {
    int aux = inv_heap[x];
    swap(inv_heap[x], current_heap_size--);
    
    if(x == current_heap_size + 1) return;

    urca(aux);
    coboara(aux);
}

int get_min_heap() {
    return store[heap[1]];
}

int main() {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    
    scanf("%d", &N);
    
    int op_type, val, x;
    for(int i = 1; i <= N; i++) {
        scanf("%d", &op_type);
        
        switch(op_type) {
            case 1:
                scanf("%d", &val);
                insert_in_heap(val);
            break;
            case 2:
                scanf("%d", &x);
                delete_from_heap(x);
            break;
            case 3: 
                printf("%d\n", get_min_heap());
            break;
            default: return 0;
        }
    }
    
    return 0;
}