Cod sursa(job #1981671)

Utilizator MaligMamaliga cu smantana Malig Data 16 mai 2017 14:02:39
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>

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

#define ll long long
#define ui unsigned int
#define pb push_back
const int NMax = 2e5 + 5;

int N,M;
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 swap_heap(int,int);

int main() {
    in>>M;

    int nrInsert = 0;
    while (M--) {
        int tip,x,pos;
        in>>tip;

        switch (tip) {
        case 1:
            in>>x;
            heap[++N] = elem(x,++nrInsert);
            idx[N] = nrInsert;
            percolate(N);

            break;
        case 2:
            in>>x;

            pos = idx[x];
            swap_heap(pos,N);
            --N;

            if (pos != 1 && heap[pos].val < heap[pos/2].val) {
                percolate(pos);
            }
            else {
                sift(pos);
            }

            break;
        case 3:

            out<<heap[1].val<<'\n';
        }
    }

    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(node,son);

            node = son;
        }
        else {
            son = 0;
        }
    }
    while (son);
}

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

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

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