Cod sursa(job #2746049)

Utilizator cosmin1812Nedelcu Adrian Cosmin cosmin1812 Data 27 aprilie 2021 13:47:47
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include<fstream>
#include<assert.h>
using namespace std;

int n, l, nr, a[200010], heap[200010], poz[200010];

void push(int x) {
	int aux;
	while (x / 2 != 0 && a[heap[x]] < a[heap[x / 2]]) {
		aux = heap[x];
		heap[x] = heap[x / 2];
		heap[x / 2] = aux;

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


void pop(int x) {
	int aux, k;
	k = 0;
	while (x != k) {
		k = x;

		if (k * 2 <= l && a[heap[x]] > a[heap[k * 2]])
			x = k * 2;

		if (k * 2 + 1 <= l && a[heap[x]] > a[heap[k * 2 + 1]])
			x = k * 2 + 1;

		aux = heap[x];
		heap[x] = heap[k];
		heap[k] = aux;

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

int main()
{
	ifstream f("heapuri.in");
	ofstream g("heapuri.out");

	int i, x, k, ok = 1;
	cout << "n = "; cin >> n;

	if (1 > n || n > 200000)
		ok = 0;

	for (i = 1; i <= n && ok == 1; i++) {
		cout << "k = "; cin >> k;

		if (1 > k || k > 3) {
			ok = 0;
			break;
		}

		if (k < 3) {
			cout << "x = "; cin >> x;
			if (1 > x || x > 1000000000) {
				ok = 0;
				break;
			}
		}

		if (k == 1) {
			l++;
			nr++;
			a[nr] = x;
			heap[l] = nr;
			poz[nr] = l;
			push(l);
		}

		if (k == 2) {

			a[x] = -1;

			if (poz[x] == 0) {
				ok = 0;
				break;
			}

			if (1 > x || x > nr) {
				ok = 0;
				break;
			}

			push(poz[x]);

			poz[heap[1]] = 0;
			heap[1] = heap[l--];
			poz[heap[1]] = 1;
			if (l > 1)
				pop(1);
		}

		if (k == 3)
			cout << a[heap[1]];
	}
	if (ok == 0)
		cout << "eroare";

	return 0;
}