Cod sursa(job #1988111)

Utilizator MaligMamaliga cu smantana Malig Data 2 iunie 2017 08:29:13
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <queue>

using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");

#define ll long long
#define pb push_back
const int NMax = 2e5 + 5;
const ll inf = 1e9 + 5;

int N,M,nrInsert;
int idx[NMax];

struct elem {
    int val,ord;
    elem(int _val = 0,int _ord = 0) {
        val = _val;
        ord = _ord;
    }
}heap[NMax];

void percolate(int);
void sift(int);
void swapHeap(int,int);

int main() {
    in>>M;

    for (int i=1;i <= M;++i) {
        int tip,x;
        in>>tip;

        switch (tip) {
        case 1: {
            in>>x;

            heap[++N] = elem(x,++nrInsert);
            idx[nrInsert] = N;
            percolate(N);

            break;
        }
        case 2: {
            in>>x;

            int pos = idx[x];
            swapHeap(idx[x],N--);
            //swap(idx[x],idx[heap[N].ord]])

            int dad = pos / 2;
            if (heap[pos].val < heap[dad].val) {
                percolate(pos);
            }
            else {
                sift(pos);
            }

            break;
        }
        case 3: {
            out<<heap[1].val<<'\n';
        }
        }
    }

    in.close();out.close();
    return 0;
}

void percolate(int node) {
    int dad = node/2;
    while (node != 1 && heap[node].val < heap[dad].val) {
        swapHeap(node,dad);

        node = dad;
        dad = node/2;
    }
}

void sift(int node) {
    int son;
    do {
        son = 0;
        int fs = node<<1, ss = fs + 1;
        if (fs <= N) {
            son = fs;
            if (ss <= N && heap[ss].val < heap[fs].val) {
                son = ss;
            }
        }

        if (son && heap[son].val < heap[node].val) {
            swapHeap(son,node);
            node = son;
        }
        else {
            son = 0;
        }
    }
    while (son);
}

void swapHeap(int x,int y) {
    swap(idx[heap[x].ord],idx[heap[y].ord]);
    swap(heap[x],heap[y]);
}