Cod sursa(job #3163302)

Utilizator TeodoraMaria123Serban Teodora Maria TeodoraMaria123 Data 31 octombrie 2023 11:15:34
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.46 kb
#include <bits/stdc++.h>

using namespace std;

vector <int> position;

class heap
{
    int heapSize;
    vector <pair <int, int> > v;

    void up(int poz)
    {
        bool ok = 1;
        while(poz / 2 > 0 &&  ok)
        {
            ok = 0;
            if(v[poz] < v[poz / 2])
            {
                swap(position[v[poz].second], position[v[poz / 2].second]);
                swap(v[poz], v[poz / 2]);
                ok = 1;
            }

            poz >>= 1;
        }
    }

    void down(int poz)
    {
        bool ok = 1;
        while(poz * 2 <= heapSize &&  ok)
        {
            int child = 2 * poz;
            ok = 0;
            if(child + 1 <= heapSize  &&  v[child] > v[child + 1])
            {
                child ++;
            }
            if(v[poz] > v[child])
            {
                swap(position[v[poz].second], position[v[child].second]);
                swap(v[poz], v[child]);
                poz = child;
                ok = 1;
            }
        }
    }

public :

    heap ()
    {
        v.resize(1);
        heapSize = 0;
    }

    void push(int val, int ord)
    {
        v.push_back({val, ord});
        heapSize ++;
        up(heapSize);
    }

    void pop(int poz)
    {
        swap(v[poz], v[heapSize]);
        swap(position[v[poz].second], position[v[heapSize].second]);
        v.pop_back();
        heapSize --;
        down(poz);
        up(poz);
    }

    int top()
    {
        return v[1].first;
    }

    int Size()
    {
        return heapSize;
    }
    void print()
    {
        for(int i = 1; i <= heapSize; i ++)
            cout << v[i].first <<" ";
        cout << "\n";
    }
};

int main()
{
    ios_base :: sync_with_stdio(0);
    cin.tie(0);

    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    int n;
    cin >> n;

    heap pq;
    int cnt = 0;
    position.push_back(0);

    for(int i = 1; i <= n; i ++)
    {
        int x;
        cin >> x;
        if(x == 1)
        {
            int val;
            cin >> val;
            position.push_back(pq.Size() + 1);
            pq.push(val, ++cnt);
        }
        else if(x == 2)
        {
            int poz;
            cin >> poz;
            pq.pop(position[poz]);
        }
        else
        {
            cout << pq.top() << "\n";
//            pq.print();
        }
    }
    return 0;
}