Cod sursa(job #1442724)

Utilizator ramhackNastase Ramon ramhack Data 26 mai 2015 08:42:51
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.41 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <fstream>

#define BUFFLEN 256

using namespace std;


class MinHeap {

private:
	//vector<int> heapArray;
	int *heapArray;
	int crt_size;
public:

	MinHeap(int size) : crt_size(0) {
		heapArray = new int[size + 1];
	}

	~MinHeap() {}

	int parent(int poz) {
		return poz / 2;
	}
	int rightChild(int poz) {
		return poz * 2 + 1;
	}
	int leftChild(int poz) {
		return poz * 2;
	}

	int peekHeap() {
		return heapArray[1];
	}
	void insertHeap(int elem) {

		crt_size++;
		heapArray[crt_size] = elem;
		pushUp(crt_size);
	}
	int popHeap(int node) {

		int minElem = heapArray[node];
		heapArray[crt_size] = minElem;
		//heapArray[node] = heapArray[crt_size];
		crt_size--;
		
		if(node > 1 && (heapArray[node] < heapArray[parent(node)])) {
			pushUp(node);
		}
		else {
			pushDown(this->crt_size, node);
		}
		return minElem;
	}

	void pushDown(int poz, int node) {


		int son = 0;

		do {
			son = 0;

			if(leftChild(node) <= poz) {
				son = leftChild(node);

				if(rightChild(node) <= poz && heapArray[rightChild(node)] < heapArray[leftChild(node)] ) {
					son = rightChild(node);
				}

				if(heapArray[son] >= heapArray[node]) {
					son = 0;
				}
			}
			if(son) {
				swap(heapArray[node], heapArray[son]);
				node = son;
			}


		} while(son);


	}

	void pushUp( int node) {

		int key = heapArray[node];

		while(node > 1 && (key < heapArray[parent(node)])) {
			heapArray[node] = heapArray[parent(node)];
			node = parent(node);
		}

		heapArray[node] = key;

	}

};


int main(int argc, char const *argv[])
{

	ifstream inFile; inFile.open("heapuri.in");
	ofstream outFile; outFile.open("heapuri.out");
	
	string line;
	int N, operatie, value;
	//inFile >> N;
	
	getline(inFile,line);
	N = line[0] - '0';
	MinHeap heap(N);

	cout << N << endl;


	for(int i = 0; i < N; i++) {

		getline(inFile, line);
		//cout << line << endl;
		
		if(line.size() > 1) {
		
			operatie = line[0] - '0';
			value = line[2] - '0';
		
			if(operatie == 1) {
				cout << "inserting " << value << endl;
				heap.insertHeap(value);
			}
			else if(operatie == 2) {
				heap.popHeap(value);
				cout << "Deleting " << value << " poz element" << endl;
			}
		}
		else {
			operatie = line[0] -'0';
		
			if(operatie == 3) {
				int min = heap.peekHeap();
				outFile << min << endl	;
				cout << "Result : "  << min << endl;
			}
		}
	}



	inFile.close();
	outFile.close();

	return 0;
}