Cod sursa(job #1535811)

Utilizator kassay_akosKassay Akos kassay_akos Data 25 noiembrie 2015 10:47:38
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <iostream>
#include <string.h>

using namespace std;

const int nmax = 200002;
int v[nmax], heap[nmax], pos[nmax], nr = 0, len = 0, root = 0;

inline int father(int x) { return x / 2; };
inline int left  (int x) { return x * 2 ; };
inline int right (int x) { return x * 2 + 1; };

void ins(int val);
void del(int ind);

int main(){
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	int m,x,a;
	scanf("%d ", &m);
	for (; m--;) {
		scanf("%d", &x);
		switch (x)
		{
		case 1:
			scanf("%d", &a);
			ins(a);
			break;
		case 2:
			scanf("%d", &a);
			del(a);
			break;
		case 3:
			printf("%d \n", v[heap[1]]);
			break;
		}
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}


void ins(int val){
	v[++nr] = val;
	heap[++len] = nr;
	pos[nr] = len;
	int x = len;
	while (v[heap[x]] < v[heap[father(x)]] && x > 1) {
		swap(heap[x], heap[father(x)] );
		pos[heap[x]] = x;
		pos[heap[father(x)]] =  father(x);
		x = father(x);
	}
}

void del(int iedik) {
	v[iedik] = -1;
	heap[pos[iedik]] = heap[len];
	pos[heap[len--]] = pos[iedik];
	
	int x = pos[iedik];			// index of the swaped number
	//going up
	while (v[heap[x]] < v[heap[father(x)]] && x > 1) {
		swap(heap[x], heap[father(x)]);
		pos[heap[x]] = x;
		pos[heap[father(x)]] = x = father(x);
	}

	// going down
	bool q = true;
	while (q && left(x) <= len) {
		q = false;
		if (right(x) <= len) {
			if (v[heap[left(x)]] < v[heap[right(x)]] && v[heap[left(x)]] < v[heap[x]] ) {
				swap(heap[left(x)], heap[x]);
				pos[heap[x]] = x;
				pos[heap[left(x)]] = x = left(x);
				q = true;
			}
			else if (heap[right(x)] < heap[x]) {
				swap(heap[right(x)], heap[x]);
				pos[heap[x]] = x;
				pos[heap[right(x)]] = x = right(x);
				q = true;
			}
		}
		else if (heap[x] > heap[left(x)]) {
			swap(heap[left(x)], heap[x]);
			pos[heap[x]] = x;
			pos[heap[left(x)]] = x = left(x);
			q = true;
		}
	}

}