Cod sursa(job #709413)

Utilizator DSzprogDombi Szabolcs DSzprog Data 8 martie 2012 08:22:02
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <cstring>
#include <cstdio>
#include <cmath>

const int size = 200002;

int a[size];
int pos[size];
int heap[size];
int n, m;

void push(int c) {
	int p = c / 2;
	while (p) {
		if (a[heap[c]] < a[heap[p]]) {
			int swap = heap[c];
			heap[c] = heap[p];
			heap[p] = swap;
		} else {
			break;
		}
		pos[heap[c]] = c;
		pos[heap[p]] = p;
		c = p;
		p /= 2;
	}
}

void pop(int p) {
	int c = p * 2;
	if (c < m) {
		c = (a[heap[c]] < a[heap[c + 1]]) ? c : c + 1;
	}
	while (c <= m) {
		if (a[heap[c]] < a[heap[p]]) {
			int swap = heap[c];
			heap[c] = heap[p];
			heap[p] = swap;
		} else {
			break;
		}
		pos[heap[c]] = c;
		pos[heap[p]] = p;
		p = c;
		c = p * 2;
		if (c < m) {
			c = (a[heap[c]] < a[heap[c + 1]]) ? c : c + 1;
		}
	}
}

void add(int x) {
	a[++n] = x;
	heap[++m] = n;

	pos[n] = m;
	push(m);
}

void del(int x) {
	heap[pos[x]] = heap[m];
	pos[m--] = pos[x];
	pop(pos[x]);
	push(pos[x]);
}

int root() {
	return(a[heap[1]]);
}

int main() {
	FILE * in = fopen("heapuri.in", "rt");
	FILE * out = fopen("heapuri.out", "wt");

	int count;
	fscanf(in, "%d", &count);
	while (count--) {
		int type;
		fscanf(in, "%d", &type);
		if (type == 3) {
			fprintf(out, "%d\n", root());
		} else {
			int id;
			fscanf(in, "%d", &id);
			if (type == 1) {
				add(id);
			} else {
				del(id);
			}
		}
	}

	fclose(in);
	fclose(out);
}