Cod sursa(job #1248559)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 25 octombrie 2014 15:25:15
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 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 x) {
    int aux;

    while (x/2 && V[H[x]]<V[H[x/2]])
    {
        aux = H[x];
        H[x] = H[x/2];
        H[x/2] = aux;

        P[H[x]] = x;
        P[H[x/2]] = x/2;
        x /= 2;
    }
}

void goDown (int x) {

    int aux, y = 0;

    while (x != y)
    {
        y = x;

        if (y*2<=index && V[H[x]]>V[H[y*2]]) x = y*2;
        if (y*2+1<=index && V[H[x]]>V[H[y*2+1]]) x = y*2+1;

        aux = H[x];
        H[x] = H[y];
        H[y] = aux;

        P[H[x]] = x;
        P[H[y]] = y;
    }
}

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;
}