Cod sursa(job #393838)

Utilizator Addy.Adrian Draghici Addy. Data 10 februarie 2010 00:33:09
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <stdio.h>
#define Nmax 200050

int v[Nmax], P[Nmax], H[Nmax], T, n, k, i, x, tip;

void up(int i) {
	int t, c, aux;
	
	t = i >> 1, c = i;
	while (t > 0 && v[H[c]] < v[H[t]]) {
		aux = H[c], H[c] = H[t], H[t] = aux;
		P[H[c]] = c, P[H[t]] = t;
		
		c = t, t = c >> 1;
	}
}

void down(int i) {
	int t, c, aux;
	
	t = i, c = i << 1;
	if (c + 1 <= n && v[H[c+1]] < v[H[c]])
		c++;
	
	while (c <= n && v[H[t]] > v[H[c]]) {
		aux = H[c], H[c] = H[t], H[t] = aux;
		P[H[c]] = c, P[H[t]] = t;
		
		t = c, c = t << 1;
		
		if (c + 1 <= n && v[H[c+1]] < v[H[c]])
			c++;
	}
}

void cut(int i) {
	
	H[i] = H[n], P[H[i]] = i;
	n--;
	
	if (P[i] > 1 && v[H[i]] < v[H[i>>1]])
		up(i);
	else
		down(i);
}

int main() {
	
	FILE *f = fopen("heapuri.in", "r");
	FILE *g = fopen("heapuri.out", "w");
	
	fscanf(f, "%d", &T);
	
	for ( ; T > 0; T--) {
		fscanf(f, "%d", &tip);
		
		if (tip == 1) {
			fscanf(f, "%d", &x);
			n++, k++;
			
			v[k] = x, H[n] = k, P[k] = n;
			
			up(n);
		} else 
			if (tip == 2) {
				fscanf(f, "%d", &x);
				
				cut(P[x]);
			}
			else if (tip == 3)
				fprintf(g, "%d\n", v[H[1]]);
	}
	
	fclose(f); fclose(g);
	
	return 0;
}