Cod sursa(job #1248558)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 25 octombrie 2014 15:24:17
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 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 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;
}