Cod sursa(job #1757819)

Utilizator catalincraciunCraciun Catalin catalincraciun Data 15 septembrie 2016 21:57:16
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>

#define NMax 400005
#define inf 1500000
#define father(x) x/2
#define leftChild(x) 2*x
#define rightChild(x) 2*x+1

using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int n, nodes;
int V[NMax]; // Keeps the values
int A[NMax]; // Keeps the nodes
int P[NMax];

void heapify(int node) {
	if (node > 1) {
		if (V[A[node]] < V[A[father(node)]]) {
//			cout<<"Changing node "<<V[A[node]]<<" with node "<<V[A[father(node)]]<<endl;
			int aux = A[node];
			A[node] = A[father(node)];
			A[father(node)] = aux;

			P[A[node]] = node;
			P[A[father(node)]] = father(node);

			heapify(father(node));
		}
	}	
}

void deletify(int node) {
	if (leftChild(node) <= nodes) {
		int val = V[A[leftChild(node)]];
		int poz = leftChild(node);

		if (rightChild(node) <= nodes) {
			if (val > V[A[rightChild(node)]]) {
				val = V[A[rightChild(node)]];
				poz = rightChild(node);
			}
		}

//		cout<<"Delete - Changing node "<<V[A[node]]<<" with node "<<V[A[poz]]<<endl;
		int aux = A[node];
		A[node] = A[poz];
		A[poz] = aux;

		P[A[node]]= node;
		P[A[poz]] = poz;	
		
		deletify(poz);
	}
}

void read() {

	// Init
	nodes = 0;

	f>>n;
	while (n--) {
		int tip; f>>tip;
		if (tip == 1) {
			int x;
			f>>x;
		
			nodes++;
			V[nodes] = x;
			A[nodes] = nodes;
			P[nodes] = nodes;
			
			heapify(nodes);	
		} else if (tip == 2) {
			int p;
			f>>p;
			
			V[p] = inf;
			deletify(P[p]);			
		} else {
			g<<V[A[1]]<<'\n';
		}
	}
}

int main() {

	read();

	f.close();
	g.close();

	return 0;
}