Cod sursa(job #2200154)

Utilizator EclipseTepes Alexandru Eclipse Data 30 aprilie 2018 14:54:47
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
#include <fstream>
#define dMAX 200000

using namespace std;

int n, o, x;
int heap[dMAX + 2], idx;
int history[dMAX + 2], p;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

void RestoreMinHeap() {
    int myPos, father;
    myPos = idx;
    father = myPos / 2;
    while (father && heap[myPos] < heap[father]) {
        swap(heap[myPos], heap[father]);
        myPos = father;
        father /= 2;
    }
}

void InsertInHeap(int a) {
    heap[++idx] = a;
    history[++p] = a;
}

void RemoveFromHeap(int a) {
    int i, j, poz = 0;
    for (i = 1; i <= idx; i++) {
        if (heap[i] == history[a]) {
            poz = i;
            break;
        }
    }
    swap(heap[poz], heap[idx--]);
    int child = poz;
    while ((heap[poz] > heap[child] || heap[poz] > heap[child + 1])
           && (heap[child] || heap[child + 1])) {
        if (heap[child] && heap[child + 1]) {
            if (heap[child] < heap[child + 1]) {
                swap(heap[poz], heap[child]);
                poz = child;
                child *= 2;
            } else {
                swap(heap[poz], heap[child + 1]);
                child++;
                poz = child;
                child *= 2;
            }
        } else {
            if (heap[child]) {
                swap(heap[poz], heap[child]);
                poz = child;
                child *= 2;
            } else {
                swap(heap[poz], heap[child + 1]);
                child++;
                poz = child;
                child *= 2;
            }
        }
    }

}

int main()
{
    int i, j;
    fin >> n;
    for (i = 1; i <= n; i++) {
        fin >> o;
        switch (o) {
        case 1:
            fin >> x;
            InsertInHeap(x);
            RestoreMinHeap();
            break;
        case 2:
            fin >> x;
            RemoveFromHeap(x);
            break;
        case 3:
            fout << heap[1] << '\n';
            break;
        }
    }
    return 0;
}