Cod sursa(job #2134350)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 17 februarie 2018 21:08:01
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>

using namespace std;

ifstream in("heap.in");
ofstream out("heap.out");

MAXN = 2e5;

int heap[MAXN + 10], v[MAXN + 10], poz[MAXN + 10];

int NR = 0, L = 0;

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 upHeap(int nod){
	while (nod > 1 && heap[father(nod)] >= heap[nod]){
		swap(heap[father(nod)], heap[nod]);
		swap(pos[nod], pos[father(nod)]);
		nod = father(nod);
	}
}

void downHeap(int nod){

	while (left_son(nod) <= n || right_son(nod) <= n){
		if(heap[right_son(nod)] >= heap[nod]){
			swap(heap[right_son(nod)], heap[nod]);
			swap(poz[right_son(nod), poz[nod]]);
		}
		else if (heap[left_son(nod)] >= heap[nod]){
			swap(heap[left_son(nod)], heap[nod]);
			swap(poz[left_son(nod), poz[nod]]);
		}
		else
			break;
	}

}

int main(){

	int cod;
	int n;

	in >> n;

	for (int i = 1; i <= n; ++ i){
		in >> cod;

		if (cod == 1){
			in >> v[++NR];
			poz[NR] = ++L;
			heap[L] = v[NR];
			upHeap(L);
		}
		if (cod == 2){
			in >> x;
			heap[poz[x]] = heap[L];
			heap[L] = 0;
			poz[L] = poz[x];
			poz[x] = 0;
			--L;

			downHeap(poz[L]);
			upHeap(poz[L]);
		}
		if (cod == 3){
			out << heap[1] << '\n';
		}
	}

	
	return 0;
}