Cod sursa(job #407205)

Utilizator vasilemureVasile Mure vasilemure Data 2 martie 2010 09:58:28
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <stdio.h>
#include <algorithm>

#define INF 1<<30
#define Nmax 200010

using namespace std;

int H[Nmax], poz[Nmax], nr[Nmax];
int i, j, q, x, t, c, n, aux, niv, aux1;

void UP(int i){
	
	t = i/2;
	c = i;
	aux = H[c];
	aux1 = c;
	while (H[t] > aux && t > 0){
		H[c] = H[t];
		poz[c] = t;		
		nr[t] = c;
		c = t;
		t = c/2;
	}
	H[c] = aux;
	poz[c] = aux1;
	nr[aux1] = c;
}

int DOWN(int i, int n){
	
	c = 2*i;
	t = i;
	
	while ((H[t] > H[c] && c <= n) || (H[t] > H[c+1] && c+1 <= n)){
		if (H[c + 1] < H[c] && (c + 1) <= n)
			c = c + 1;
		
		aux = H[t];
		H[t] = H[c];
		H[c] = aux;
		
		nr[poz[t]] = t;
		nr[poz[c]] = c;
		
		aux1 = poz[t];
		poz[t] = poz[c];
		poz[c] = aux1;
		t = c;
		c = 2*t;
	}	
}

int main (){
	FILE * f = fopen ("heapuri.in", "r");
	FILE * g = fopen ("heapuri.out", "w");
	
	fscanf (f, "%d", &n);
	niv = 0;
	for (i = 1 ; i <= n ; i++){
		fscanf (f, "%d", &q);
		if (q == 1){
			fscanf(f, "%d", &x);
			poz[++niv] = niv;
			nr[niv] = niv;
			H[niv] = x;
			UP(niv);
		}
		
		if (q == 2){
			fscanf (f, "%d", &x);
			
			x = nr[x];
			
			H[x] = H[niv];
			poz[x] = poz[niv];
			niv --;
			nr[poz[x]] = x;
			
			t = x/2;
			c = x;
			
			if (H[c] < H[t])
				UP(c);
			
			t = x;
			c = 2*x;
			
			if ((H[t] > H[c] && c <= niv) || (H[t] > H[c+1] && c+1 <= niv)){
				if (c+1 > i)
					H[c+1] = INF;
				DOWN(x,niv);
			}
			
		}
		
		if (q == 3)
			fprintf (g, "%d\n", H[1]);
	}
	
	
	fclose(g);
	fclose(f);
	return 0;
}