Cod sursa(job #501639)

Utilizator brainwashed20Alexandru Gherghe brainwashed20 Data 15 noiembrie 2010 23:01:26
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include<cstdio>
#include<algorithm>

using namespace std;

#define Nmax 200005

int H[Nmax], poz[Nmax], A[Nmax], N, NR;

int father(int nod) {
    return nod/2;
}
int left_son(int nod) {
    return nod*2;
}
int right_son(int nod) {
    return nod*2+1;
}

void percolate(int K) {
	while(K>1 && H[K]<H[father(K)]){
        swap(H[K],H[father(K)]);
		swap(A[K],A[father(K)]);
        poz[A[K]]=K;
        poz[A[father(K)]]=father(K);
        K=father(K);
    }
}

void sift(int K) {
	int son=K;
	if(left_son(K)<=N) 
		son=2*K;
	if(right_son(K)<=N) 
		son=2*K+1;
	if(son!=K) {
		swap(H[K],H[son]);
		swap(A[K],A[son]);
        poz[A[K]]=K;
        poz[A[son]]=son;
		sift(son);
	}
}

void insert(int K) {
    NR++; N++;
    H[N]=K;
	A[N]=NR;
    poz[NR]=N;
    percolate(N);
}

void cut(int K){
	K=poz[K];
    H[K]=H[N];
    N--;
	if(K>1 && H[K]<H[father(K)])
		percolate(K);
    else
		sift(K);
}

int main() {
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
    int M, tip, val;
	for(scanf("%d",&M); M; --M) {
		scanf("%d",&tip);
        switch(tip) {
		case 1:
			scanf("%d",&val);
			insert(val);
			break;
		case 2:
			scanf("%d",&val);
            cut(val);
			break;
		default:
			printf("%d\n",H[1]);
			break;
		}
	}
    return 0;
}