Cod sursa(job #2409520)

Utilizator kodama cheama alex koda Data 19 aprilie 2019 10:09:16
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>

using namespace std;

const int N = 200000;

int v[N], poz[N], h[N], nh;

void schimba (int p, int q) {
    int aux = h[p];
    h[p] = h[q];
    h[q] = aux;
    poz[h[p]] = p;
    poz[h[q]] = q;
}

void urca (int p) {
    while ( p > 1 && v[h[p]] < v[h[p/2]] ) {
        schimba(p,p/2);
        p /= 2;
    }
}

void adauga ( int val ) {
    h[++nh] = val;
    poz[h[nh]] = nh;
    urca(nh);
}

void coboara ( int p ) {
    int fs = 2 * p, fd = 2 * p + 1, bun = p;
    if ( fs <= nh && v[h[fs]] < v[h[bun]] )
        bun = fs;
    if ( fd <= nh && v[h[fd]] <v[h[bun]] )
        bun = fd;
    if ( bun != p ) {
        schimba(p,bun);
        coboara (bun);
    }
}

void sterge ( int p ) {
    if ( p == nh )
        nh --;
    else {
        schimba(p,nh--);
        urca(p);
        coboara(p);
    }
}

int main () {
    ifstream fin ("heapuri.in");
    ofstream fout ("heapuri.out");
    int optype, n, x;
    fin>>n;
    int hm = 0;
    for ( int i = 0; i < n; i++ ) {
        fin>>optype;
        switch (optype) {
        case 1 :
            fin>>x;
            v[hm++] = x;
            adauga(hm-1);
            break;
        case 2 :
            fin>>x;
            sterge(poz[x-1]);
            break;
        case 3 :
            fout<<v[h[1]]<<'\n';
        }
    }
    return 0;
}