Cod sursa(job #1261098)

Utilizator diana97Diana Ghinea diana97 Data 11 noiembrie 2014 22:31:24
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int NMAX = 200000 + 1;
const int INF = 1 << 30;

int n, q, height;
int v[NMAX], heap[2 * NMAX], pozitie[NMAX];

void schimb(int x, int y) {
    pozitie[heap[x]] = y;
    pozitie[heap[y]] = x;

    swap(heap[x], heap[y]);
}

void urca(int poz) {
    while (1 < poz && v[heap[poz / 2]] > v[heap[poz]]) {
        schimb(poz, poz / 2);
        poz /= 2;
    }
}

void coboara(int poz) {
    while (2 * poz <= height) {
        if (2 * poz + 1 >= height || v[heap[2 * poz]] < v[heap[2 * poz + 1]]) {
            schimb(poz, 2 * poz);
            poz = 2 * poz;
        }
        else {
            schimb(poz, 2 * poz + 1);
            poz = 2 * poz + 1;
        }
    }
}

void insereaza() {
    heap[height++] = n;
    pozitie[n] = height - 1;
    urca(pozitie[n]);
}

void sterge(int x) {
    int poz = pozitie[x];
    heap[poz] = heap[height - 1];
    height--;
    if (heap[poz / 2] > heap[poz]) urca(poz);
    else coboara(poz);
}

void rezolva() {
    int t, a;
    f >> q;
    n = height = 1;
    while(q--) {
        f >> t;
        if (t == 1) {
            f >> v[n];
            insereaza();
            n++;
        }
        else if (t == 2) {
            f >> a;
            sterge(a);
        }
        else g << v[heap[1]] << '\n';
    }
}

int main() {
    rezolva();
    return 0;
}