Cod sursa(job #1248556)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 25 octombrie 2014 15:22:05
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#define NMax 200005
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");

int n;
int key, index;
int H[NMax], V[NMax], P[NMax];

void goUp (int k) {
    while (k>1 && V[H[k]] < V[H[k/2]]) {
        int aux = H[k];
        H[k] = H[k/2];
        H[k/2] = aux;

        P[k] = k/2;
        P[k/2] = k;
    }
}

void goDown (int k) {

    int son = 0;

    do {
        int son = 0;

        if (2*k<=index && V[H[k]] > V[H[k*2]]) {
            son = 2*k;
            if (2*k+1<=index && V[H[son]] > V[H[2*k+1]])
                son = 2*k+1;

            int aux = H[son];
            H[son] = H[k];
            H[k] = aux;

            P[H[son]] = son;
            P[H[k]] = k;

            k = son;
        } else if (2*k+1<=index && V[H[k]] > V[H[2*k+1]]) {
            son = 2*k;

            int aux = H[son];
            H[son] = H[k];
            H[k] = aux;

            P[H[son]] = son;
            P[H[k]] = k;

            k = son;
        }
    } while (son != 0);
}

int main() {

    f>>n;
    for (int i=1;i<=n;i++) {
        int type;
        f>>type;
        if (type == 1) {
            int x; f>>x;
            key++; index++;
            V[key] = x;
            H[index] = key;
            P[key] = index;

            goUp (index);
        } else if (type == 2) {
            int ord; f>>ord;
            int posInHash = P[ord];
            H[posInHash] = H[index];
            P[ord] = -1;
            index--;

            if (posInHash > 1 && V[H[posInHash]] < V[H[posInHash/2]])
                goUp (posInHash);
            else
                goDown (posInHash);
        } else if (type == 3) {
            g<<V[H[1]]<<'\n';
        }
    }

    f.close(); g.close();

    return 0;
}