Cod sursa(job #2895859)

Utilizator AdelaCorbeanuAdela Corbeanu AdelaCorbeanu Data 29 aprilie 2022 15:39:26
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <fstream>
#include <vector>
#include <map>

std::vector<int> heap;      /// indices of values in heap
std::vector<int> values;    ///values in order of insertion
std::map<int, int> position; ///position of index of a value in heap  <i, index of i in heap>

void swap_nodes (int index1, int index2) {
    std::swap(heap[index1], heap[index2]);
    std::swap(position[heap[index1]], position[heap[index2]]);
}

void ReheapUp (int index) {
    while (index) {
        int father = (index - 1) / 2;
        if (values[father] > values[index]) swap_nodes(father, index), index = father;
        else return;
    }
}

void ReheapDown (int index) {

        int child1 = index * 2 + 1;
        int child2 = index * 2 + 2;

        if (child1 == heap.size()) return;

        if (child2 == heap.size() || values[heap[child1]] < values[heap[child2]]) {
            if (values[heap[child1]] < values[heap[index]]) {
                swap_nodes(index, child1);
                ReheapDown(child1);
                return;
                //index = child1;
            }
            else return;
        }
        else {
            if (values[heap[child2]] < values[heap[index]] && child2 < heap.size()) {
                swap_nodes(index, child2);
                ReheapDown(child2);
                return;
                //index = child2;
            }
            else return;
        }

}

void push (int value) {
    values.push_back(value);
    heap.push_back(values.size() - 1);
    position[values.size() - 1] = heap.size() - 1;
    ReheapUp(heap.size() - 1);
}

void pop (int index) {
    swap_nodes(position[index], heap.size() - 1);

    position.erase(index);
    heap.pop_back();

    int father = (position[index] - 1) / 2;
    if (values[heap[father]] > values[heap[position[index]]]) ReheapUp(position[index]);
    else ReheapDown(position[index]);
}

int main()
{
    std::ifstream fin("heapuri.in");
    std::ofstream fout("heapuri.out");
    int n;
    fin >> n;
//    heap.push_back(-1);
    values.push_back(-1);
    for (int i = 0; i < n; ++i) {
        int op;
        fin >> op;

        if (op == 3) fout << values[heap[0]] << '\n';
        else {
            int x;
            fin >> x;
            if (op == 1) push(x);
            else pop(x);
        }
    }

    return 0;
}