Cod sursa(job #1025205)

Utilizator Alina_MariaMateescu Adina Lenuta Maria Alina_Maria Data 9 noiembrie 2013 16:53:11
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.71 kb
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>

//maximum of operations
#define maxN 200000
#define MAX_HEAP_SIZE 10000000
using namespace std;
int minHeap[MAX_HEAP_SIZE], hn, n, operations[maxN], cnt[maxN], poz[maxN], contor;

int father(int nod) {
    return nod / 2;
}

int rightSon(int nod) {
    return 2 * nod + 1;
}

int leftSon(int nod) {
    return 2 * nod;
}

int minimumValue() {
    return minHeap[1];
}

void swapHeapValues(int a, int b) {
    int aux = cnt[a];
    cnt[a] = cnt[b];
    cnt[b] = aux;

    aux = poz[cnt[a]];
    poz[cnt[a]] = poz[cnt[b]];
    poz[cnt[b]] = aux;

    aux = minHeap[a];
    minHeap[a] = minHeap[b];
    minHeap[b] = aux;
}

void down_heap(int k) {
    int son, sonR, sonL;
    do {
        son = 0;
        sonL = leftSon(k);
        if(sonL <= hn) {//pentru ca sa nu ieie si frunzele (adica ele nu au fii) si oricum ele in heap sunt deja asezate
                // nu exista pos. ca mai jos de ele sa fie ceva cu o valoare mai mare decat ele caci nu exista nimic
            son = sonL;
            sonR = rightSon(k);
            if (sonR <= hn && minHeap[sonR] < minHeap[sonL]) {
                son = sonR;
            }
            if (minHeap[son] >= minHeap[k]) {
                son = 0;
            }
        }

        if(son) {
            swapHeapValues(son, k);
            k = son;
        }
    }while(son);
}

void up_heap(int k) {
    while(k > 1 && minHeap[k] < minHeap[father(k)]) {
        int parent = father(k);
        swapHeapValues(k, parent);
        k = parent;
    }
}

void cutAnElement(int k) {
    swapHeapValues(k, hn);
    --hn;
    down_heap(k);
    up_heap(k);

}

void insetAnElement(int key) {
    minHeap[++hn] = key;
    cnt[hn] = contor;
    poz[contor] = hn;
    up_heap(hn);
}

void buildHeap() {
    for(int i = hn / 2; i >= 1; --i)
        down_heap(i);
}

void sortHeap() {
    buildHeap();
    for(int i = hn; i >= 2; --i) {
        swapHeapValues(i, 1);
        --hn;
        down_heap(1);
    }
}

void readOperations() {
    int  opI, num;
    for(int i = 0; i < n; ++i) {
        scanf("%d", &opI);
        if(opI == 1) {
            scanf("%d", &num);
            ++contor;
            insetAnElement(num);
            continue;
        }
        if(opI == 2) {
            scanf("%d", &num);
            cutAnElement(poz[num]);
            continue;
        }
        if(opI == 3) {
            printf("%d\n", minHeap[1]);
            continue;
        }
    }
}

int main() {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    scanf("%d ", &n);
    readOperations();
    return 0;
}