Cod sursa(job #1279594)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 30 noiembrie 2014 16:55:36
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <iostream>
#include <fstream>

#define NMax 200005

using namespace std;

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

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

void heapDown(int x) {

    while (x < heapSize) {
        int minim = V[H[x]];
        int pminim = x;

        if (x * 2 <= heapSize) {
            if (minim > V[H[2*x]]) {
                pminim = 2*x;
                minim = V[H[2*x]];
            }
        }
        if (2*x+1 <= heapSize) {
            if (minim > V[H[2*x+1]]) {
                pminim = 2*x+1;
                minim = V[H[2*x+1]];
            }
        }

        if (pminim != x) {
            int aux = H[x];
            H[x] = H[pminim];
            H[pminim] = aux;

            P[H[x]] = x;
            P[H[pminim]] = pminim;

            x = pminim;
        } else {
            break;
        }
    }
}

void heapUp(int x) {

    int aux;
    while (x > 1) {
        if (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;
        } else
            break;
    }
}

int main() {

    heapSize = index = 0;
    f>>n;
    for (int i=1;i<=n;i++) {
        int type, x;
        f>>type;
        if (type == 1) {
            f>>x;
            heapSize++; index++;
            V[index] = x;
            H[heapSize] = index;
            P[index] = heapSize;
            heapUp(heapSize);
        } else if (type == 2) {
            f>>x;
            int positionToErase = P[x];
            H[positionToErase] = H[heapSize];
            P[H[positionToErase]] = positionToErase;
            heapSize--;
            if (positionToErase > 1 && V[H[positionToErase]]<V[H[positionToErase/2]])
                heapUp(positionToErase);
            else
                heapDown(positionToErase);
        } else if (type == 3) {
            g<<V[H[1]]<<'\n';
        }
    }

    f.close(); g.close();
    return 0;
}