Cod sursa(job #2255274)

Utilizator manutrutaEmanuel Truta manutruta Data 6 octombrie 2018 17:39:24
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#include <iostream>
#include <fstream>

#define father(x) (x >> 1)
#define left_son(x) (x << 1)
#define right_son(x) ((x << 1) +1)


using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");

#define MAX 200010
int heap[MAX], sz;
int poz[MAX],v[MAX], szv,n;
int getMin()
{
    return heap[1];
}

void insert(int sz)
{
    while(father(sz) >= 1 &&
          v[heap[father(sz)]] > v[heap[sz]])
    {
        swap(heap[father(sz)], heap[sz]);
        swap(poz[heap[father(sz)]], poz[heap[sz]]);
    }
}

void popH()
{
    swap(heap[1],heap[sz]);
    swap(poz[heap[1]], poz[heap[sz]]);
    sz--;

    int i=1;
    while(right_son(i) <= sz &&
          (v[heap[i]] > v[heap[left_son(i)]] || v[heap[i]] > v[heap[right_son(i)]]))
    {
        if (v[heap[right_son(i)]] > v[heap[left_son(i)]])
        {
            swap(heap[i], heap[left_son(i)]);
            swap(poz[heap[i]], poz[heap[left_son(i)]]);
            i = left_son(i);
        }
        else
        {
            swap(heap[i], heap[right_son(i)]);
            swap(poz[heap[i]], poz[heap[right_son(i)]]);
            i = right_son(i);
        }
    }
    if (left_son(i) <= sz && v[heap[left_son(i)]] < v[heap[i]])
    {
        swap(heap[i], heap[left_son(i)]);
        swap(poz[heap[i]], poz[heap[left_son(i)]]);
    }
}
int main()
{
    f>>n;
    int op,x;
    for(int i=1;i<=n;i++)
    {
        f >> op;
        switch(op)
        {
            case 1:
            {
                f >> x;
                szv++;
                v[szv] = x;

                sz++;
                heap[sz] = szv;

                poz[szv] = sz;
                insert(sz);
            } break;

            case 2:
            {
                f >> x;
                v[x] = -1;
                insert(poz[x]);
                popH();
            } break;

            case 3:
            {
                g << v[getMin()] << '\n';
                break;
            }
        }
        /*cout << op << ' ' << x << endl;
        for (int i = 1; i <= szv; ++i)
        {
            cout << v[i] << ' ';
        }
        cout << endl;
        for (int i = 1; i <= szv; ++i)
        {
            cout << poz[i] << ' ';
        }
        cout << endl;
        for (int i = 1; i <= sz; ++i) {
            cout << heap[i] << ' ';
        }
        cout << endl << endl;

        system("pause");*/
    }
    return 0;
}