Cod sursa(job #1193899)

Utilizator pavlov.ionPavlov Ion pavlov.ion Data 2 iunie 2014 12:01:30
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include<stdio.h>
#include<algorithm>
const int MAX_HEAP_SIZE = 200000;
typedef int Heap[MAX_HEAP_SIZE];

inline int father(int nod) {
    return nod / 2;
}

inline int left_son(int nod) {
    return nod * 2;
}

inline int right_son(int nod) {
    return nod * 2 + 1;
}
inline int min(Heap H) {
    return H[1];
}
void swap(int &x,int &y) {
	int aux;
	aux=x;
	x=y;
	y=aux;
}
void sift(Heap H, int N, int K) {
    int son;
    do {
        son = 0;
        // Alege un fiu mai mare ca tatal.
        if (left_son(K) <= N) {
            son = left_son(K);
            if (right_son(K) <= N && H[right_son(K)] < H[left_son(K)]) {
                son = right_son(K);
            }
            if (H[son] >= H[K]) {
                son = 0;
            }
        }

        if (son) {
            swap(H[K], H[son]);  // Functie STL ce interschimba H[K] cu H[son].
            K = son;
        }
    } while (son);
}
void percolate(Heap H, int N, int K) {
    int key = H[K];

    while ((K > 1) && (key < H[father(K)])) {
        H[K] = H[father(K)];
        K = father(K);
    }

    H[K] = key;
}
void cut(Heap H, int& N, int K) {
    H[K] = H[N];
    --N;

    if ((K > 1) && (H[K] < H[father(K)])) {
        percolate(H, N, K);
    } else {
        sift(H, N, K);
    }
}
void insert(Heap H, int& N, int key) {
    H[++N] = key;
    percolate(H, N, N);
}
int search(Heap H,int N,int x){
	int i;
	for(i=1;i<=N;i++)
		if	(H[i]==x)
				return i;
}
int main () {
	int M,N,i,x,k,cod,y[200000];
	Heap H;
	N=0;
	k=0;
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	scanf("%d ",&M);
	for(i=1;i<=M;i++){
		scanf(" %d",&cod);
		switch(cod) {
			case 1:
						scanf("%d ",&x);
						y[++k]=x;
						insert(H,N,x);
						break;
			case 2:
						scanf("%d", &x);
						cut(H,N,search(H,N,y[x]));
						break;
			case 3:
						printf("%d\n",min(H));
	}
}
	fclose(stdin);
	fclose(stdout);
return 0;
}