Cod sursa(job #913657)

Utilizator beldeabogdanBogdan Beldea beldeabogdan Data 13 martie 2013 17:54:12
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <cstdio>
using namespace std;
 
int val[200010];
int heap[200010], id;
int pos[200010];
int t,n;
void introduce(int x);
void sterge(int x);

void introduce(int x) {
    while (x/2 >= 1 && val[heap[x]] < val[heap[x/2]]) {
        int a = heap[x];
        heap[x] = heap[x/2];
        heap[x/2] = a;
        pos[heap[x]] = x;
        pos[heap[x/2]] = x/2;
        x /= 2;
    }
}
 
void sterge(int x) {
    int a,y; bool schimbat = true;
    while (schimbat) {
		schimbat = false;
        y = x;
        if (y*2<=n && val[heap[x]] > val[heap[y*2]]) {
			x = y*2;
			schimbat = true;
		}
        if (y*2+1<=n && val[heap[x]] > val[heap[y*2+1]]) {
			x = y*2+1;
			schimbat = true;
		}
		if (schimbat) {
			a = heap[x];
			heap[x] = heap[y];
			heap[y] = a;
			pos[heap[x]] = x;
			pos[heap[y]] = y;
		}
    }
}
 
int main() {
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    int i,x,tip;
    scanf("%d",&t);
    for (i=1; i<=t; i++) {
        scanf("%d",&tip);
        if (tip == 1) {
			scanf("%d",&x);
            n++; id++;
            val[id] = x;
            heap[n] = id;
            pos[id] = n;
            introduce(n);
        } else if (tip == 2) {
			scanf("%d ", &x);
            val[x] = -1;
            introduce(pos[x]);
            pos[heap[1]] = 0;
            heap[1] = heap[n--];
            pos[heap[1]] = 1;
            if (n>1) sterge(1);
        } else if (tip == 3) {
			printf("%d\n", val[heap[1]]);
		}
    }
    return 0;
}