Cod sursa(job #2721111)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 11 martie 2021 16:18:57
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
/*
heap[node] = al catelea element introdus in multime se afla in nodul node
value[heap[node]] = valoarea elementului din nodul node al heapului, implicit si valoarea elementului introdus al
heap[node]-lea in multime
nth[i] = nodul in care se afla al i-lea element introdus in heap, deci nth[heap[node]] == node
Sift() -> coboara un element
Percolate() -> urca un element
*/

#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int NMax = 2 * 1e5;

int n, nodes, index;
int heap[NMax + 5], nth[NMax + 5], value[NMax + 5];

void Swap(int node1, int node2){
    swap(heap[node1], heap[node2]);
    nth[heap[node1]] = node1;
    nth[heap[node2]] = node2;
}

void Sift(int node){
    int leftson = 2 * node, rightson = leftson + 1, son = 0;
    if (leftson <= nodes){
        son = leftson;
        if (rightson <= nodes && value[heap[leftson]] > value[heap[rightson]])
            son = rightson;
        if (value[heap[son]] < value[heap[node]]){
            Swap(node, son);
            Sift(son);
        }
    }
}

void Percolate(int node){
    int father = node / 2;
    if (!father)
        return;
    if (value[heap[father]] > value[heap[node]]){
        Swap(father, node);
        Percolate(father);
    }
}

void Insert(int x){
    index++;
    nodes++;
    int node = nodes;
    heap[node] = index;
    value[heap[node]] = x;
    nth[heap[node]] = node;
    Percolate(node);
}

void Delete(int x){
    int node = nth[x];
    Swap(node, nodes);
    nodes--;
    int father = node / 2;
    if (value[heap[node]] < value[heap[father]])
        Percolate(node);
    else
        Sift(node);
}

void Print(){
    fout << value[heap[1]] << '\n';
}

int main(){
    fin >> n;
    while (n--){
        int type, x;
        fin >> type;
        if (type == 1){
            fin >> x;
            Insert(x);
        }
        if (type == 2){
            fin >> x;
            Delete(x);
        }
        if (type == 3)
            Print();
    }
    return 0;
}