Cod sursa(job #2232172)

Utilizator TrixerAdrian Dinu Trixer Data 17 august 2018 16:51:48
Problema Heapuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.42 kb
#include <stdio.h>

#define NMAX 200001

int n, t;
int heap[NMAX], pos[NMAX], vec[NMAX];

void swap(int *a, int *b)
{
	int aux;
	aux = *a;
	*a = *b;
	*b = aux;
}

int parent(int x)
{
	return x / 2;
}

int left_child(int x)
{
	return x * 2;
}

int right_child(int x)
{
	return x * 2 + 1;
}

void sift(int x)
{
	int left, right, child = 0;

	while (x != child) {
		child = x;
		left = left_child(x);
		right = right_child(x);

		if (left <= n && vec[heap[x]] > vec[heap[left]])
			x = left;
		if (right <= n && vec[heap[x]] > vec[heap[right]])
			x = right;

		swap(&heap[x], &heap[child]);
		pos[heap[x]] = x;
		pos[heap[child]] = child;
	}
}

void percolate(int x)
{
	while (parent(x) && vec[heap[x]] < vec[heap[parent(x)]]) {
		swap(&heap[x], &heap[parent(x)]);
		pos[heap[x]] = x;
		pos[heap[parent(x)]] = parent(x);
		x = parent(x);
	}
}

void insert(int key)
{
	n++, t++;

	vec[t] = key;
	heap[n] = t;
	pos[t] = n;

	percolate(n);
}

void erase(int x)
{
	vec[x] = -1;
	percolate(pos[x]);

	pos[heap[1]] = 0;
	heap[1] = heap[n--];
	pos[heap[1]] = 1;

	if (n > 1)
		sift(1);
}

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

	int m, x, op;
	scanf("%d", &m);
	for (int i = 0; i < m; i++) {
		scanf("%d", &op);

		switch (op) {
		case 1:
			scanf("%d", &x);
			insert(x);
			break;
		case 2:
			scanf("%d", &x);
			erase(x);
			break;
		case 3:
			printf("%d\n", vec[heap[1]]);
			break;
		}
	}

	return 0;
}