Cod sursa(job #783860)

Utilizator batistaUPB-Oprea-Cosmin-Dumitru batista Data 4 septembrie 2012 12:20:10
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include<fstream>
using namespace std;
int n,m,i,op,nr,c,v[200004],heap[200004],poz[200004];
void up(int p)
{int x=heap[p];
	while(v[x]<v[heap[p/2]] && p/2)
	{
		poz[heap[p/2]]=p;
		heap[p]=heap[p/2];
		p/=2;
	}
	heap[p]=x;
	poz[x]=p;
}
void down(int p)
{int x=heap[p];
	while( (v[x]>v[heap[2*p]] && 2*p<=n) || (v[x]>v[heap[2*p+1]] && 2*p+1<=n) )
	{
	  if(v[heap[2*p]]<v[heap[2*p+1]])p=p*2;
	   else p=p*2+1;
	  poz[heap[p]]=p/2;
	  heap[p/2]=heap[p];
	}
	heap[p]=x;
	poz[x]=p;
}
int main()//in heap retin numarul de ordine al elementelor,iar in v retin valorile elementelor 
{
	ifstream f("heapuri.in");ofstream g("heapuri.out");
	f>>m;
	for(i=1;i<=m;i++)
	{
		f>>op;
		if(op==3){g<<v[heap[1]]<<'\n';continue;}
		f>>nr;
		if(op==1)//insereaza pe nr
		{
		 v[++c]=nr;
		 heap[++n]=c;
		 up(n);
		}
		else
		if(op==2)//sterge al nr-lea numar citit
		{
			heap[poz[nr]]=heap[n--];
			up(poz[nr]);
			down(poz[nr]);
		}
	}
	f.close();g.close();
return 0;}