Cod sursa(job #1753889)

Utilizator AplayLazar Laurentiu Aplay Data 7 septembrie 2016 11:54:06
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include<bits/stdc++.h>

#define NMAX 200001
#define swapp(x, y) { int tmp = x; x = y; y = tmp; }

using namespace std;

int N, operation, element, heap[NMAX], iHeapPz[NMAX], heapPz[NMAX];

void heapInsert(int nrcrt, int element) {
    heap[++heap[0]] = element;
    iHeapPz[heap[0]] = nrcrt;
    int position = heapPz[nrcrt] = heap[0];

    while(position / 2 >= 1 && heap[position / 2] > element) {
        swapp(heap[position / 2], heap[position]);
        swapp(iHeapPz[position / 2], iHeapPz[position]);
        heapPz[nrcrt] = position / 2;
        heapPz[iHeapPz[position]] = position;
        position >>= 1;
    }
}

void heapDelete(int nrcrt) {
    if (heap[0] == 1) {
        --heap[0];
        return;
    }

    swapp(heap[heapPz[nrcrt]], heap[heap[0]]);
    iHeapPz[heapPz[nrcrt]] = iHeapPz[heap[0]];
    heapPz[iHeapPz[heap[0]]] = heapPz[nrcrt];
    --heap[0];

    int position = heapPz[nrcrt], newPosition = -1;

    while(true) {
        int left = position * 2 + 1, right = left + 1;
        newPosition = position;
        if (left <= heap[0] && heap[left] < heap[position]) newPosition = left;
        if (right <= heap[0] && heap[right] < heap[position]) newPosition = right;

        if (position != newPosition) {
            swapp(heap[newPosition], heap[position]);
            swapp(iHeapPz[newPosition], iHeapPz[position]);
            heapPz[iHeapPz[newPosition]] = newPosition;
            heapPz[iHeapPz[position]] = position;
        } else  break;
    }
}

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

    scanf("%d", &N);

    for (int it = 0; it < N; ++it) {
        scanf("%d", &operation);
        switch(operation) {
        case 1:
            scanf("%d", &element);
            heapInsert(it, element);
            break;
        case 2:
            scanf("%d", &element);
            heapDelete(element - 1);
            break;
        case 3:
            printf("%d\n", heap[1]);
            break;
        }
    }

    return 0;
}