Cod sursa(job #1626325)

Utilizator viuscenkoViktor Iuscenko viuscenko Data 3 martie 2016 00:54:16
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int N_MAX = 2e5+100;

#define FN (nod >> 1)                   /// father
#define LC (nod << 1)                   /// left child
#define RC (nod << 1) + 1               /// right child

int n, k;
int h[N_MAX], pos[N_MAX], inv[N_MAX];

void upHeap(int nod) {
    while(nod > 1 && h[FN] > h[nod]) {
        swap(h[FN], h[nod]);
        swap(pos[FN], pos[nod]);
        swap(inv[pos[FN]], inv[pos[nod]]);
        nod = FN;
    }
}

void downHeap(int nod) {
    int son;
    do {
        son = 0;
        if(LC <= k) {
            son = LC;
            if(RC <= k && h[RC] < h[son])
                son = RC;
        }

        if(h[son] >= h[nod])
            son = 0;

        if(son) {
            swap(h[son], h[nod]);
            swap(pos[son], pos[nod]);
            swap(inv[pos[son]], inv[pos[nod]]);
        }
    } while(son);
}

int main() {
    fin >> n;
    k = 0;

    int t, x, y;
    for(int i = 1; n; --n) {
        fin >> t;
        if(t == 1) {
            fin >> h[++k];
            pos[k] = i;
            inv[i] = k;
            ++i;
            upHeap(k);
        }
        if(t == 2) {
            fin >> x;
            y = inv[x];
            h[y] = h[k];
            inv[pos[k]] = y;
            pos[y] = pos[k];
            --k;
            if(y > 1 && h[y] < h[(y >> 1)])
                upHeap(y);
            else
                downHeap(y);
        }
        if(t == 3) {
            fout << h[1] << "\n";
        }
    }
}