Cod sursa(job #3318305)

Utilizator ZsomborZsombor Horvay Zsombor Data 27 octombrie 2025 21:16:37
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.81 kb
#include <fstream>
#include <vector>
#include <utility>
#include <climits>

using namespace std;

ifstream be("heapuri.in");
ofstream ki("heapuri.out");

int main()
{
    int n;
    be >> n;

    int t, x;

    vector<pair<int, int>> h;
    vector<int> order;


    for(int i = 0; i < n; i++)
    {
        be >> t;

        if(t == 1)
        {
            be >> x;
            h.push_back({x, h.size()});
            order.push_back(h.size() - 1);

            int current = h.size() - 1;

            while(current > 0)
            {
                int k = (current - 1) / 2;

                if(h[k] > h[current])
                {
                    swap(h[k], h[current]);
                    swap(order[h[k].second], order[h[current].second]);
                }else
                {
                    break;
                }

                current = k;
                k = (k - 1) / 2;
            }

        }else if(t == 2)
        {
            be >> x;
            x--;
            
            int current = order[x];

            h[current] = h.back();
            order[h.back().second] = current;
            h.pop_back();

            while(2 * current + 1 <= (int)h.size() - 1)
            {
                int c1 = 2 * current + 1;
                int c2 = -1;

                if(2 * current + 2 <= (int)h.size() - 1)
                {
                    c2 = 2 * current + 2;
                }

                if(c2 == -1)
                {
                    if(h[current].first > h[c1].first)
                    {
                        swap(h[current], h[c1]);
                        swap(order[h[current].second], order[h[c1].second]);

                        current = c1;
                    }else
                    {
                        break;
                    }

                    
                }else
                {
                    int minimum = min(h[c1].first, h[c2].first);

                    if(h[current].first > minimum)
                    {
                        if(minimum == h[c1].first)
                        {
                            swap(h[current], h[c1]);
                            swap(order[h[current].second], order[h[c1].second]);

                            current = c1;

                        }else
                        {
                            swap(h[current], h[c2]);
                            swap(order[h[current].second], order[h[c2].second]);

                            current = c1;
                        }
                    }else
                    {
                        break;
                    }
                }
            }
        }else
        {
            ki << h[0].first << "\n";
        }
    }

    return 0;
}