Cod sursa(job #1245022)

Utilizator roxana.istratePoenaru Roxana roxana.istrate Data 18 octombrie 2014 15:40:38
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <iostream>
#include <vector>
#define MAX 200000
using namespace std;

int N, K;
vector<int> H(MAX, 0);
vector<int> inserted_nodes(MAX, 0);
vector<int> whereInInserted(MAX, 0);
vector<int> posHeap(MAX, 0);

int father(int node){
	return node/2;
}

int left_son(int node){
	return 2*node;
}

int right_son(int node){
	return node*2+1;
}

void sift(int node){
	int son;
    do {
        son = 0;
        // Alege un fiu mai mare ca tatal.
        if (left_son(node) < N) {
            son = left_son(node);
            if (right_son(node) < N && H[right_son(node)] < H[left_son(node)]) {
                son = right_son(node);
            }
            if (H[son] >= H[node]) {
                son = 0;
            }
        }
  
        if (son) {
            posHeap[whereInInserted[H[node]]] = son;
			posHeap[whereInInserted[H[son]]] = node;
			swap(H[node], H[son]);
            node = son;
        }
    } while (son);
}

void percolate(int node){
	int f, key = H[node];
	while(node > 1 && key < H[f = father(node)]){
		H[node] = H[f];
		posHeap[whereInInserted[H[f]]] = node;
		node = f;
	}
	H[node] = key;
	posHeap[whereInInserted[H[node]]] = node;
}

void insertH(int elem){
	H[N] = elem;
	posHeap[whereInInserted[H[N]]] = N;
	percolate(N);
	N++;
}

void deleteH(int node){
	H[node] = H[N-1];
	posHeap[whereInInserted[H[N-1]]] = node;
	N--;
	if(node > 1 && H[node] < H[father(node)]){
		percolate(node);
	}else{
		sift(node);
	}
}

int main(){
	int M, op_code, elem, ith; 
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	scanf("%d", &M);
	K = 1, N = 1;
	for(int i = 0; i < M; i++){
		scanf("%d", &op_code);
		switch(op_code){
		case 1: 
			scanf("%d", &elem);
			inserted_nodes[K] = elem;
			whereInInserted[elem] = K;
			insertH(elem);
			K++;
			break;
		case 2:
			scanf("%d", &ith);
			deleteH(posHeap[ith]);

			break;
		case 3:
			printf("%d\n", H[1]);
		}
	}
	return 0;
}