Cod sursa(job #2747295)

Utilizator marabelu131Mara-Luciana Belu marabelu131 Data 28 aprilie 2021 23:41:57
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include<iostream>
#include<fstream>

using namespace std;
#define maxn 200010

void swap(int &a, int &b)
{
    int aux;

    aux = a;
    a = b;
    b = aux;
}

int aux, n, L, nr;
int nrV[maxn], heap[maxn], poznod[maxn];

void op1(int x)
{
	while ((x / 2) && nrV[heap[x]] < nrV[heap[x/2]]) // heap[x / 2] - tatal lui heap[x]
	{
		aux = heap[x];
		heap[x] = heap[x/2];
		heap[x/2] = aux;

		poznod[heap[x]] = x;
		poznod[heap[x/2]] = x/2;
		x /= 2;
	}
}

void op2(int x)
{
	int y = 0;

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

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

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

		aux = heap[x];
		heap[x] = heap[y];
		heap[y] = aux;

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

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

	int x, cod;

	fin >> n;

	for (int i = 1; i <= n; i++)
	{
        fin >> cod;
		if (cod != 3)
			fin >> x;

		if (cod == 1)
		{
			L++, nr++;
			nrV[nr] = x;
			heap[L] = nr;
			poznod[nr] = L;

			op1(L);
		}

		if (cod == 2)
		{
			nrV[x] = -1;
			op1(poznod[x]);

			poznod[heap[1]] = 0;
			heap[1] = heap[L--];
			poznod[heap[1]] = 1;
			if (L > 1)
                op2(1);
		}

		if (cod == 3)
            fout << nrV[heap[1]] << endl;
	}

    fin.close();
    fout.close();

	return 0;
}