Cod sursa(job #1579383)

Utilizator dorin31Geman Dorin Andrei dorin31 Data 24 ianuarie 2016 18:10:51
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>

#define maxSize 200005

using namespace std;

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

int nr,n;
int h[maxSize], ord[maxSize], poz[maxSize];

inline int father(int nod) { return nod/2; }
inline int left_son(int nod) { return nod*2; }
inline int right_son(int nod) { return nod*2+1; }

void sift(int k)
{
    int son;
    do {
        son=0;
        if (left_son(k)<=n) {
            son=left_son(k);
            if (right_son(k)<=n&&h[right_son(k)]<h[left_son(k)])
                son=right_son(k);
            if (h[son]>=h[k])
                son=0;
        }
        if (son) {
            swap(h[k],h[son]);
            swap(poz[k],poz[son]);
            k=son;
        }
    } while (son);
}

void percolate(int k)
{
    int key=h[k];
    while (k>1&&key<h[father(k)]) {
        swap (poz[k], poz[father(k)]);
        h[k]=h[father(k)];
        k=father(k);
    }
    h[k]=key;
}

void in(int &n, int val)
{
    ord[++nr]=val;
    h[++n]=val;
    poz[nr]=n;
    percolate(n);
}

void out(int &n, int k)
{
    h[k]=h[n--];
    if (k>1&&h[k]<h[father(k)]) percolate(k);
    else sift(k);
}

int main()
{
    int tasks,cod,x;
    fin>>tasks;
    while (tasks--)
    {
        fin>>cod;
        if (cod<3) {
            fin>>x;
            if (cod==1) {
                in(n,x);
            }
            if (cod==2) {
                out(n,poz[ord[x]]);
            }
        }
        else fout<<h[1]<<'\n';
    }
    return 0;
}