Cod sursa(job #611446)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 1 septembrie 2011 16:51:11
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include<fstream>
#include<vector>
using namespace std;
int heap[200200],val[200200],poz[200200],nr,l;
inline int father(int nod) {return nod/2;}
inline int left_son(int nod) {return 2*nod;}
inline int right_son(int nod) {return 2*nod+1;}
void up(int nod)
{
	while(nod/2&&val[nod]<val[father(nod)])
		{swap(heap[nod],heap[father(nod)]);
		poz[heap[nod]]=nod;
		poz[heap[father(nod)]]=father(nod);
		nod=father(nod);
		}
}
void down(int nod)
{
	int k=0;
	while(nod!=k)
		{k=nod;
		if(2*k<=l&&val[heap[k]]>val[heap[left_son(k)]]) nod=2*k;
		if(2*k+1<=l&&val[heap[k]]>val[heap[right_son(k)]]) nod=2*k+1;
		
		swap(heap[nod],heap[k]);
		
		poz[heap[nod]]=nod;
		poz[heap[k]]=k;
		}
}
int main() {
	int n, i, x, y;
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");
	in>>n;
	for(i = 0;i < n;i++) {
		in>>x;
		switch(x) {
			case 1 :{in>>y;
					nr++;l++;
					val[nr]=y;// valorile ordonate dupa timp,val[1]=prima intrata
					heap[l]=nr;// ordinea valorilor in heap ,heap[1]=vf
					poz[nr]=l;//poz valorii y in heap
					up(l);
					}break;
			case 2 :{in>>y;
					val[y]=-1;
					up(poz[y]);
					poz[heap[1]]=0;
					heap[1]=heap[l--];
					poz[heap[1]]=1;
					if(l>1) down(1);
					}break;
			case 3 :out<<val[heap[1]]<<'\n';
			}
		}
	return 0;
}