Cod sursa(job #1992700)

Utilizator MaligMamaliga cu smantana Malig Data 21 iunie 2017 09:15:04
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 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 pb push_back
#define ui unsigned int
const int inf = 1e9 + 5;
const int NMax = 2e5 + 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 swapHeap(int,int);

int main() {
    in>>M;

    while (M--) {
        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);
            --N;

            if (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<<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(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) {
        swapHeap(node,dad);
        node = dad;
        dad = node/2;
    }
}

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