Cod sursa(job #2081334)

Utilizator calin9819Costea Calin calin9819 Data 4 decembrie 2017 17:08:26
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int N, h[200001], l, poz[200001], nrT, heap[200001];

void adaug(int n) {
    while (n / 2 && h[heap[n]] < h[heap[n / 2]]) {
        int aux = heap[n];
        heap[n] = heap[n / 2];
        heap[n / 2] = aux;
        poz[heap[n]] = n;
        poz[heap[n / 2]] = n / 2;
        n /= 2;
    }
}

void sterg(int n) {

    int aux, x = 0;
    while (n != x) {
        x = n;
        if (x * 2 <= l && h[heap[n]] > h[heap[x * 2]]) n = x * 2;
        if (x * 2 + 1 <= l && h[heap[n]] > h[heap[x * 2 + 1]]) n = x * 2 + 1;
        aux = heap[n];
        heap[n] = heap[x];
        heap[x] = aux;
        poz[heap[n]] = n;
        poz[heap[x]] = x;
    }
}


int main() {
    f >> N;
    for (int i = 1; i <= N; i++) {
        int t;
        f >> t;
        if (t == 3)
            g << h[heap[1]] << '\n';
        else {
            int nr;
            f >> nr;
            if (t == 1) {
                l++;
                nrT++;
                h[nrT] = nr;
                poz[nrT] = l;
                heap[l] = nrT;
                adaug(l);
            } else {
                h[nr] = -1;
                if (poz[nr] == 0) return 0;
                if (nr < 1 || nr > nrT) return 0;
                adaug(poz[nr]);
                poz[heap[1]] = 0;
                heap[1] = heap[l--];
                poz[heap[1]] = 1;
                if (l > 1) sterg(1);
            }
        }
    }
    return 0;
}