Cod sursa(job #962967)

Utilizator gabrieligabrieli gabrieli Data 16 iunie 2013 11:09:16
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.64 kb
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

const size_t MAXN = 200010;
// Heap data type and comparator.
typedef int heap_t;
inline bool cmp_heap(const heap_t &a, const heap_t &b)
{return a < b;}
// The data
heap_t data[MAXN]; // 1 based index
size_t size_data;
/* Contains the indexes of the data organized as
 * a min or a max heap, the top being at position 1.
 */
size_t heap[MAXN], size_heap;
// pos[i] is the position of data[i] in the heap.
size_t pos_heap[MAXN]; 

// Moves the element at heap[pos] up in the heap.
void heap_up(size_t pos)
{
	while (pos/2 && !cmp_heap(data[heap[pos/2]], data[heap[pos]]))
	{
		swap (heap[pos], heap[pos/2]);
		pos_heap[heap[pos]] = pos;
		pos_heap[heap[pos/2]] = pos/2;
		pos /= 2;
	}
}
// Moves the element at heap[pos] down in the heap.
void heap_down(size_t pos)
{
	size_t next;
	while (pos <= size_heap)
	{
		next = pos;
		if (2*pos <= size_heap && !cmp_heap(data[ heap[next] ], data[ heap[pos*2] ]))
			next = 2*pos;
		if (2*pos+1 <=  size_heap && !cmp_heap(data[ heap[next] ], data[ heap[pos*2+1] ]))
			next = 2*pos+1;

		if (next == pos) break;

		swap (heap[pos], heap[next]);
		pos_heap[heap[next]] = next;
		pos_heap[heap[pos]] = pos;
		
		pos = next;
	}
}
 
// Adds the element data[pos] to the heap.
void push_heap(const size_t pos)
{
	heap[++size_heap] = pos;
    pos_heap[pos] = size_heap;
    heap_up(size_heap);
}
// Returns the element at the top of the heap.
heap_t top_heap()
{ return data[heap[1]]; }
// This removes element data[pos] from the heap.
void delete_heap(size_t pos)
{
	pos = pos_heap[pos];

	swap(heap[pos], heap[size_heap]);
	pos_heap[heap[pos]] = pos;
	pos_heap[heap[size_heap]] = size_heap;

	size_heap -= 1;

	heap_down(pos);
}
// Removes the element at the top of the heap.
heap_t pop_heap()
{
	heap_t temp = data[heap[1]];
    delete_heap(1);
	return temp;
}
// Initializes the heap.
void init_heap(heap_t *data, const size_t size_data)
{
	for (size_t i = 1; i <= size_data; ++i)
		heap[i] = pos_heap[i] = i;

	size_heap = size_data;
	for (size_t i = size_data/2; i; --i)
		heap_down(i);
}
// After modifying data[pos] this maintains the heap propery.
void update_heap(size_t pos)
{
	pos = pos_heap[pos];

	heap_up(pos);
	heap_down(pos);
}

int main() 
{
	ifstream fin("heapuri.in");
	ofstream fout("heapuri.out");

	size_t t, op, x;
	fin >> t;

	for (; t; --t)
	{
		fin >> op;
		switch(op)
		{
			case 1:
				fin >> x;
				data[++size_data] = x;
                push_heap(size_data);

				break;
			case 2:
				fin >> x;
                delete_heap(x);

				break;
			case 3:
				fout << top_heap() << '\n';

				break;
		}
	}

	fout.close();
	return EXIT_SUCCESS;
}