Cod sursa(job #2747418)

Utilizator marabelu131Mara-Luciana Belu marabelu131 Data 29 aprilie 2021 01:36:08
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <iostream>

using namespace std;


int A[200010], heap[200010], poz[200010];
int n, cod, L, nr;

void push(int x)
{
	while (x / 2 && A[heap[x]] < A[heap[x/2]])
	{
		swap(heap[x],heap[x/2]);

		poz[heap[x]] = x;
		poz[heap[x/2]] = x/2;
		x /= 2;
	}
}
 void pop(int x)
{
	int  y = 0;

	while (x != y)
	{
		y = x;

		if (y * 2 <= L && A[heap[x]] > A[heap[y*2]])
            x = y * 2;
		if (y * 2 + 1 <= L && A[heap[x]] > A[heap[y*2+1]])
            x = y * 2 + 1;

        swap(heap[x],heap[y]);

		poz[heap[x]] = x;
		poz[heap[y]] = y;
	}
}


int main()
{
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

    fin>>n;

    int x;

    for(int i=0;i<n;i++)
    {
        fin >> cod;

        if(cod == 3)
            fout<<A[heap[1]]<< endl;
        else
        {
            fin>>x;
            if(cod==2)
            {
                A[x]=-1;
                push(poz[x]);;
                poz[heap[1]]=0;
                heap[1]=heap[L--];
                poz[heap[1]]=1;

                if(L>1)
                    pop(1);
            }

            if(cod==1)
            {
                L++;
                nr++;
                A[nr]=x;
                heap[L]=nr;
                poz[nr] = L;
                push(L);
            }
        }
    }

    return 0;
}