Cod sursa(job #3129114)

Utilizator arobyRobert Acsente aroby Data 12 mai 2023 17:46:07
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.52 kb
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
class Heap
{
public:
    vector<int> heap;
    void push(int val)
    {
        heap.push_back(val);
        sift_up(heap.size() - 1);
    }
    int pop()
    {
        if (heap.size() == 0)
            return 0;
        else if (heap.size() == 1)
        {
            int aux = heap.back();
            heap.pop_back();
            return aux;
        }
        int val_min = heap[0];
        swap(heap.front(), heap.back());
        heap.pop_back();
        sift_down(0);
        return val_min;
    }
    void sift_down(int i)
    {
        while (2 * i + 1 < heap.size())
        {
            int l_i = 2 * i + 1;
            int r_i = 2 * i + 2;
            int min_child = l_i;
            if (r_i < heap.size() && heap[r_i] < heap[l_i])
                min_child = r_i;
            if (heap[i] > heap[min_child])
            {
                swap(heap[i], heap[min_child]);
                i = min_child;
            }
            else
                break;
        }
    }
    void sift_up(int i)
    {
        while (i > 0 && heap[i] < heap[(i - 1) / 2])
        {
            swap(heap[i], heap[(i - 1) / 2]);
            i = (i - 1) / 2;
        }
    }
    void remove(int x)
    {
        for (int i = 0; i < heap.size(); i++)
            if (heap[i] == x)
               { 
        swap(heap[i], heap.back());
        heap.pop_back();
        sift_up(i);
        sift_down(i);
        break;}
    }
};
vector<int> v;
int main()
{
    Heap my_heap;
    int n;
    in >> n;
    for (int i = 0; i < n; i++)
    {
        int x, y;
        in >> x;

        if (x == 1)
        {
            in >> y;
            v.push_back(y);
            my_heap.push(y);
        }
        else if (x == 2)
        {
            in >> y;
            // for (int i = 0; i < v.size(); i++)
            //     // if (v[i] == y)
            //     // {
            //     //     v.erase(v.begin() + i );
            //     //     break;
            //     // }
            //     cout<<v[i]<<" ";
            my_heap.remove(v[y+1]);
        }
        else
           { 
            // for (int i = 0; i < v.size(); i++)
            //     if (v[i] == y)
            //     {
            //         v.erase(v.begin() + i );
            //         break;
            //     }
                out << my_heap.pop() << endl;

           }
    }
}