Cod sursa(job #2001304)

Utilizator MaligMamaliga cu smantana Malig Data 16 iulie 2017 13:24:21
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <stack>

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

#define ll long long
#define pb push_back
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 swap_heap(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];
            swap_heap(pos,N);
            --N;

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

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) {
            swap_heap(son,node);
            node = son;
        }
        else {
            son = 0;
        }
    }
    while (son);
}

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