Cod sursa(job #1978264)

Utilizator MaligMamaliga cu smantana Malig Data 7 mai 2017 11:53:08
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

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

#define pb push_back
#define ll long long
const int NMax = 2e5 + 5;
const int 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 sift(int);
void percolate(int);
void ins(int);
void rem(int);
void swap_heap(elem&,elem&);

int main()
{
    in>>M;

    N = nrInsert = 0;
    while (M--) {
        int tip;
        in>>tip;

        switch (tip) {
        case 1: {
            int val;
            in>>val;

            ins(val);

            break;
        }
        case 2: {
            int ord;
            in>>ord;

            rem(ord);

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

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

void sift(int node) {

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

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

void percolate(int node) {

    int dad = node / 2;
    while (node != 1 && heap[dad].val > heap[node].val) {
        swap_heap(heap[node],heap[dad]);
        node = dad;

        dad = node / 2;
    }
}

void ins(int val) {

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

void rem(int ord) {

    int pos = idx[ord];
    swap_heap(heap[pos],heap[N]);
    --N;

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

void swap_heap(elem& a,elem& b) {
    swap(idx[a.ord],idx[b.ord]);
    swap(a,b);
}