Cod sursa(job #1165016)

Utilizator SRaduRadu Szasz SRadu Data 2 aprilie 2014 13:38:23
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>

using namespace std;

const int MAX = 202202;

int N, M, Last;
int V[MAX], H[MAX], Poz[MAX];

void MoveUp(int nod) {
    int dad = nod / 2;
    if(dad && V[ H[dad] ] > V[ H[nod] ]) {
        swap(H[nod], H[dad]);
        Poz[ H[nod] ] = nod;
        Poz[ H[dad] ] = dad;
        
        MoveUp(dad);
    }
}

void MoveDown(int nod) {
    int leftSon = (nod << 1), rightSon = ((nod << 1) | 1), change = nod;
    if(leftSon <= Last && V[ H[nod] ] > V[ H[leftSon] ])
        change = leftSon;
    if(rightSon <= Last && V[ H[nod] ] > V[ H[rightSon] ]) {
        if(change != nod) {
            if(V[ H[change] ] > V[ H[rightSon] ])
               change = rightSon;
        } else change = rightSon;
    }

    swap(H[nod], H[change]);
    Poz[ H[nod] ] = nod;
    Poz[ H[change] ] = change;

    if(change != nod)
        MoveDown(change);
}

int main() {
    ifstream in("heapuri.in"); ofstream out("heapuri.out");
    in >> M;
    for(int i = 1, op, X; i <= M; i++) {
        in >> op;
        if(op < 3) {
            in >> X;
            if(op == 1) {
                V[++N] = X;
                H[++Last] = N;
                Poz[N] = Last;
                MoveUp(Last);
            } else {
                V[X] = -1;
                MoveUp(Poz[X]);
                
                Poz[ H[1] ] = 0; 
                H[1] = H[Last--];
                Poz[ H[1] ] = 1;
                if(Last > 1) 
                    MoveDown(1);
            }
        } else {
            out << V[ H[1] ] << "\n";
        }
    }
}