Cod sursa(job #3248692)

Utilizator BucsMateMate Bucs BucsMate Data 12 octombrie 2024 18:01:46
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#include <iostream>
#include <fstream>
#include <vector>

const int INF = 2000000000;

using namespace std;

ifstream input("heapuri.in");
ofstream output("heapuri.out");

struct Node
{
    int value;
    int order = 0;
};

vector<Node> heapp;
vector<int> order_to_pos(1, 0);

void swap_Nodes(Node &a, Node &b)
{
    int temp = a.value;
    a.value = b.value;
    b.value = temp;

    temp = a.order;
    a.order = b.order;
    b.order = temp;
}

void push(int x)
{
    heapp.push_back({x, order_to_pos.size()});
    order_to_pos.push_back(heapp.size()-1);

    int index = heapp.size()-1;
    int parent = index/2;

    while(heapp[index].value < heapp[parent].value){
        swap_Nodes(heapp[index], heapp[parent]);
        order_to_pos[heapp[index].order] = index;
        order_to_pos[heapp[parent].order] = parent;
        index = parent;
        parent = index/2;
    }
}

void heapify_down(int index)
{
    int left = 2*index;
    int right = 2*index + 1;
    int min_index = index;
    heapp.push_back({0, 0});
    if(left < heapp.size() && heapp[left].value < heapp[index].value){
        min_index = left;
    }
    if(right < heapp.size() && heapp[right].value < heapp[min_index].value){
        min_index = right;
    }
    if(min_index != index){
        swap_Nodes(heapp[index], heapp[min_index]);
        order_to_pos[heapp[index].order] = index;
        order_to_pos[heapp[min_index].order] = min_index;

        heapify_down(min_index);
    }
}

int num(Node a)
{
    return a.value;
}

int main()
{
    int N;
    input >> N;
    for(int i = 0; i < N; i++){

        /*for(int j = 1; j < curr_index.size(); j++){
            cout << curr_index[j] << " ";
        }
        cout << endl;*/

        int operation;
        input >> operation;
        if(operation == 1){
            int x;
            input >> x;
            push(x);
        }
        else if(operation == 2){
            int x;
            input >> x;
            int index = order_to_pos[x];
            heapp[index].value = INF;
            heapify_down(index);
        }
        else{
            output << heapp[0].value << endl;
        }
    }
    return 0;
}