Cod sursa(job #2124879)

Utilizator epermesterNagy Edward epermester Data 7 februarie 2018 18:09:55
Problema Radix Sort Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include<fstream>
#include<vector>
using namespace std;

struct numbers {
	int value;
	int poz;
};

vector<numbers> heap;
vector<int> ido;

void swap(int poz1, int poz2) {
	int aux = heap[poz1].value;
	heap[poz1].value = heap[poz2].value;
	heap[poz2].value = aux;

	aux = ido[heap[poz1].poz];
	ido[heap[poz1].poz] = ido[heap[poz2].poz];
	ido[heap[poz2].poz] = aux;

	aux = heap[poz1].poz;
	heap[poz1].poz = heap[poz2].poz;
	heap[poz2].poz = aux;
}

void heapifyUp(int i) {
	if (i > 0) {
		int j = (i + 1) / 2 - 1;
		if (heap[i].value < heap[j].value) {
			swap(i, j);
			heapifyUp(j);
		}
	}
}

void heapifyDown(int i) {
	int n = heap.size();
	int j = i * 2 + 1;
	if (i * 2 + 2 < n && heap[i * 2 + 2].value < heap[j].value)
		j = i * 2 + 2;
	if (heap[j].value < heap[i].value) {
		swap(i, j);
		if (j * 2 + 1 < n) heapifyDown(j);
	}
}

void heapAdd(int x) {
	int j = heap.size();
	numbers temp;
	ido.push_back(j);
	temp.poz = ido.size()-1;
	temp.value = x;
	heap.push_back(temp);

	heapifyUp(j);
}

void heapDel(int i) {
	int j = heap.size() - 1;
	if (j == ido[i])
		heap.pop_back();
	else {
		int temp = ido[i];
		swap(ido[i], j);
		heap.pop_back(); 
		if (temp * 2 + 1 < j) heapifyDown(temp);
	}
}

int main() {
	ofstream out("heapuri.out");
	ifstream in("heapuri.in");
	int N;	
	for(in>>N;N;--N)
	{
		short command;
		in >> command;
		switch (command)
		{
		case 1: 
			int nr;
			in >> nr;
			heapAdd(nr);
			break;
		case 2:
			int pozt;
			in >> pozt;
			heapDel(pozt-1);
			break;
		case 3:
			out << heap[0].value <<"\n";
		default:
			break;
		}
	}
}