Cod sursa(job #1217823)

Utilizator ArkinyStoica Alex Arkiny Data 8 august 2014 13:19:17
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include<iostream>
#include<fstream>
using namespace std;

   int heap[1000000];
	int i;
	int pos[200100];
	int t[200100];
	int pr=1;
class Heap
{
private:
	void order_up(int  position)
	{
		while(position!=1 && heap[position/2] > heap[position])
		{
		  swap(heap[position],heap[position/2]);
		  swap(t[pos[position]],t[pos[position/2]]);
		  swap(pos[position],pos[position/2]);
		  position=position/2;
		}
		
		
	}
	void order_down(int position)
	{
		int child;
		do
		{
			if(position*2<i)
			{
			  if((position*2+1)<i)
			  {
		         child = (heap[position*2] < heap[position*2+1]) ? position*2 : (position*2 + 1);
			  }
			  else
			  {
				 child=position*2;
				 
			  }
			if(heap[position]>heap[child])
			{
			  swap(heap[position],heap[child]);
			  swap(t[pos[position]],t[pos[child]]);
		      swap(pos[position],pos[child]);

			  position=child;
			}
			else
				break;
			}
		}while(position*2<i);

		
	}
public:
	Heap(){i=1;}
	void add_to_heap(int value)
	{
		heap[i]=value;
		pos[i]=pr;
		t[pr]=i;
		order_up(i++);
		pr++;
	}

	void delete_from_heap(int id)
	{

		int position=t[id];
		swap(heap[position],heap[i-1]);
		swap(t[pos[position]],t[pos[i-1]]);
		swap(pos[position],pos[i-1]);

		--i;
		if(position/2 >1 && heap[position/2]>heap[position])
		{
			order_up(position);
		}
		else
		{
			order_down(position);
		}
	}

	int getMin()
	{
		return heap[1];
	}


};

void exec(const char *name_i,const char *name_o)
{
	Heap heap;
	ifstream f(name_i);
	ofstream fo(name_o);
	int lines;
	f>>lines;
	int operation;
	for(int j=1;j<=lines;j++)
	{
		f>>operation;
		if(operation==1)
		{
			int  value;
			f>>value;
			heap.add_to_heap(value);

		}else if(operation==2)
		{
			int elem;
			f>>elem;
			heap.delete_from_heap(elem);
		}
		else if(operation==3)
		{
			if(i>1)
			 fo<<heap.getMin()<<endl;
			
		}
	}
	f.close();
	fo.close();
}

int main()
{
	exec("heapuri.in","heapuri.out");
	return 0;
}